Can I pass an object instance method to a method waiting for a callback in Scala?

Let's say I have a method that expects another method as a parameter. Can I send object instance methods for this parameter? How can I handle methods that don't have parameters?

I will write some pseudo code:

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, for example:

val a = new ArrayList()

How can I send a method addas a parameter to myMethod1, and a method sizeas a parameter to myMethod2?

+5
source share
3 answers

, myMethod4 , , : " a.size ?".

def myMethod1(f: Int => Unit): Unit = f(1)

def myMethod2(f: () => Int): Unit = {
  val value = f // f is function, taking no arguments, and returning an int.
                // we invoke it here.
  ()
}

def myMethod3(f: => Int): Unit = {
  val value = f // f is call by name parameter.
  ()
}

def myMethod4[A](f: A => Int, a: A): Unit = {
  val value = f(a)
  ()
}

import java.util.ArrayList

val a = new ArrayList[Int](1)
myMethod1((i: Int) => a.add(i))
myMethod1(a.add(_))     // shorthand for the above
myMethod2(() => a.size) // a.size is not evaluated, it is enclosed in an anonymous function definition.
myMethod3(a.size)       // a.size is not evaluated here, it is passed as a by-name parameter.
myMethod4((al: ArrayList[Int]) => al.size, a)
myMethod4((_: ArrayList[Int]).size, a)
myMethod4[ArrayList[Int]](_.size, a)
+4

Scala

(Types,To,Pass) => ReturnType

( parens, ), -

myObject.myMethod _

, - Java:

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]

( , ArrayList , - , void.)

+5
def myMethod(callback : Int => Unit, size : => Int) = ...

myMethod(a.add _, a.size)

Void Unit.

: => Int, size , , .

+4

All Articles