Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function value of a instance method in Scala

How do I get the function value f of an instance method?

class X(i : Int){
    def method(y : Int) = y + i
}

val x = new X(10)
val f : (Int) => Int = ?

val r = x.method(2)
val r2 = f(2)

Calling x.method(2) and f(2) would be the same method call.

like image 434
Thomas Jung Avatar asked Sep 20 '09 06:09

Thomas Jung


People also ask

What does :+ mean in Scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.

What is function values in Scala?

In Scala, functions are first-class values in the sense that they can be: passed to and returned from functions. put into containers and assigned to variables. typed in a way similar to ordinary values. constructed locally and within an expression.

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 .


2 Answers

scala> class X(i : Int){ def method(y : Int) = y + i }

defined class X

scala> val x = new X(10)

x: X = X@15b28d8

scala> val f = x.method _

f: (Int) => Int = <function>

scala> val r = x.method(2)

r: Int = 12

scala> val r2 = f(2)

r2: Int = 12
like image 80
Eastsun Avatar answered Sep 20 '22 12:09

Eastsun


this useful reference indicates that methods don't have functions, functions have methods - however if you wanted to make a function from a method perhaps this is what you want:

scala> def m1(x:Int) = x+3
m1: (Int)Int
scala> val f2 = m1 _
f2: (Int) => Int = <function>
like image 43
Timothy Pratley Avatar answered Sep 19 '22 12:09

Timothy Pratley