Search code examples
functionscalaclassmember

scala, using class member function as first class functions


I want to assign a member function of a class instance as a first class function to a variable:

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

We can get the desired effect by assigning an appropriate anonymous function. Is this the only way? I searched but could find no reference at all.


Solution

  • Use a placeholder to indicate it is partially applied:

    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
    

    EDIT

    Trying the code out in the REPL prints

    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
                     ^