Let's say I have a method expecting another method as a parameter. Is it possible to send an object's instance methods for that parameter? How would I handle methods that have no parameters?
I'll write some pseudocode:
void myMethod1(callback<void,int> otherFunc); // imagine a function returning void, and taking a int parameter
void myMethod2(callback<int,void> otherFunc); // function returning void, not taking params
if for example I have an ArrayList, like this:
val a = new ArrayList()
how could I send it's add
method as parameter for myMethod1
, and it's size
method as parameter for myMethod2
?
A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle.
=> 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 .
In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).
One function can be passed to another function as a function argument (i.e., a function input parameter). The definition of the function that can be passed in as defined with syntax that looks like this: "f: Int > Int" , or this: "callback: () > Unit" .
The type of a function in Scala is denoted
(Types,To,Pass) => ReturnType
(you can leave off the parens if there is only a single type to pass), and the way to convert a method into a function to pass to another method is
myObject.myMethod _
So, putting these together--and paying attention to the types of the Java classes:
scala> def addMySize(adder: Int => Boolean, sizer: () => Int) = adder(sizer())
addMySize: ((Int) => Boolean,() => Int)Boolean
scala> val a = new java.util.ArrayList[Int]()
a: java.util.ArrayList[Int] = []
scala> addMySize(a.add _, a.size _)
res0: Boolean = true
scala> addMySize(a.add _, a.size _)
res1: Boolean = true
scala> println(a)
[0, 1]
(Note that ArrayList has an add that takes an object and returns a boolean--not one that returns void.)
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