Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain Function objects from methods in Scala?

Suppose I have a simple class in Scala:

class Simple {
  def doit(a: String): Int = 42
}

How can I store in a val the Function2[Simple, String, Int] that takes two arguments (the target Simple object, the String argument), and can call doit() get me the result back?

like image 889
Jean-Philippe Pellet Avatar asked Jul 13 '10 15:07

Jean-Philippe Pellet


People also ask

Are functions objects in Scala?

Functions are ObjectsIn Scala, we talk about object-functional programming often.

What is difference between function and method in Scala?

Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .


3 Answers

val f: Function2[Simple, String, Int] = _.doit(_)
like image 124
sepp2k Avatar answered Oct 19 '22 05:10

sepp2k


same as sepp2k, just using another syntax

val f = (s:Simple, str:String) => s.doit(str)
like image 21
hbatista Avatar answered Oct 19 '22 07:10

hbatista


For those among you that don't enjoy typing types:

scala> val f = (_: Simple).doit _
f: (Simple) => (String) => Int = <function1>

Following a method by _ works for for any arity:

scala> trait Complex {                        
     |    def doit(a: String, b: Int): Boolean
     | }                                      
defined trait Complex

scala> val f = (_: Complex).doit _            
f: (Complex) => (String, Int) => Boolean = <function1>

This is covered by a combination of §6.23 "Placeholder Syntax for Anonymous Functions" and §7.1 "Method Values" of the Scala Reference

like image 22
retronym Avatar answered Oct 19 '22 05:10

retronym