Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass an object's instance method to a method expecting a callback in Scala?

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?

like image 276
Geo Avatar asked Jan 18 '10 17:01

Geo


People also ask

What kind of parameters are not needed while calling a method in Scala?

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.

What does => mean 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 .

Is Scala pass by reference?

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).

How do you pass a function to a function in Scala?

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" .


1 Answers

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.)

like image 192
Rex Kerr Avatar answered Sep 24 '22 01:09

Rex Kerr