【问题标题】:scala, using class member function as first class functionsscala,使用类成员函数作为第一类函数
【发布时间】:2015-03-12 11:43:29
【问题描述】:

我想将类实例的成员函数作为第一类函数分配给变量:

class A(val id:Int){ def f(u:Int)=id+u }
val a= new A(0)
val h=a.f         // fails: interpreted as a.f(with missing parameter u)
val h1 = (u:Int)=>a.f(u)    // OK and does what we want

我们可以通过分配一个合适的匿名函数来获得想要的效果。 这是唯一的方法吗? 我搜索了但根本找不到参考。

【问题讨论】:

    标签: function scala class member


    【解决方案1】:

    使用占位符表示它已部分应用:

    scala> class A(val id:Int){ def f(u:Int)=id+u }
    defined class A
    
    scala> val a = new A(0)
    a: A = A@46a7a4cc
    
    scala> val h = a.f _
    h: Int => Int = <function1>
    
    scala> h(2)
    res0: Int = 2
    

    编辑

    在 REPL 打印中尝试代码

    scala> val h = a.f
    <console>:9: error: missing arguments for method f in class A;
    follow this method with `_' if you want to treat it as a partially applied function
           val h = a.f
                     ^
    

    【讨论】:

    • 谢谢!我在哪里可以找到这些信息(除了这里)?
    • @michaelmeyer 在 scala REPL 中尝试代码通常会显示有用的错误消息。我编辑了我的答案以在此处显示相关的答案。
    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2010-11-03
    相关资源
    最近更新 更多