Jus12
Jus12

Reputation: 18034

Canonical way to define and execute a method that outputs Unit?

I have a list of methods (functions) that output Unit:

var fns:List[() => Unit] = Nil
def add(fn:() => Unit) = fns :+= fn      // a method to add to the list

I want to add println("hello") to the list.

add(() => println("hello"))  

Is there a better way than using the ugly parenthesis.

I would have preferred:

add (println("hello"))  // error here 

def myCoolMethod = {
   // do something cool
   // may return something, not necessarily Unit
}
add (myCoolMethod) // error here

I tried var fns:List[_ => Unit] and var fns:List[Any => Unit], fns:List[() => Any], etc without getting what I want.

Second question is how do I execute the methods in the list when I want to. I got it to work with:

fns foreach (_.apply) 

Is there a better way?

Upvotes: 0

Views: 58

Answers (1)

senia
senia

Reputation: 38045

You could use by-name parameter instead of function with empty parameters list like this:

var fns:List[() => Unit] = Nil
def add(fn: => Unit) = fns :+= (fn _)

add{ print("hello ") }

def myCoolMethod = { println("world") }
add(myCoolMethod)

fns foreach {_.apply}
// hello world

You could use _() instead of _.apply: fns foreach {_()}, but I'd prefer _.apply.

Upvotes: 4

Related Questions