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.
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.
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.
=> 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 .
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With