noncom
noncom

Reputation: 4992

Scala - use a passed function with _ parameter

If I have the following code:

val wows = Buffer[Wow]()

def yo(f: _ => Wow) { wows += f }

and I get an error when trying to add f. I wonder, how can I use f inside the method body, or more precisely, how should I refer to it since f or f() or f(_) do not work.

UPDATE:

The type of f cannot be changed to f: => Wow because the functions of type _ => Wow passed to this method come from such a class:

object Wonderful {

    val wows = Buffer[Wow]()

    def yo(f: _ => Wow) { wows += f }
}

class Joy[+R](fs: Buffer[_ => R]) {

    def exalt() {
        fs.map(Wonderful.yo(_))
    }
}

and that buffer cannot be parametrized with => R, it shows an error.

UPDATE 2: Both of you have second-answered before I have finished the explanation of the second part! Thanks! That's the speed!

UPDATE 3: Basically, I am learning Scala and I am trying to try out all that I can think of. In this particular piece of code, there happens the following thing: I have 3 basic classes:

The main point is that a Funset's collection of "generative" functions can be edited during runtime, that is why it is represented as buffer. On every update cycle an Emitter passes each of Funsets functions to the World's creator functions that manifest the generated objects in the world.

I hope I have explained so it can be understood... maybe a little bizzare or a wrong architecture, but.. anyways, I have learned something about Scala now!

Upvotes: 0

Views: 501

Answers (2)

Calum
Calum

Reputation: 5926

_ => Wow is a method that takes a single argument of a type that you don't know and returns a Wow. You won't be able to call it since you don't know what sort of argument to call it with!

I suspect you want a method with no arguments, which you could do like the following:

def yo( f: () => Wow ) { wows += f() }

Also you can do a by-name parameter which is a little bit more implicit:

def you( f: => Wow ) { wows += f }

Edit: The difference is in how you call it; a by-name parameter just evaluates an expression when it is used. Passing a function is actually just passing a function which you can call at will.

Upvotes: 2

missingfaktor
missingfaktor

Reputation: 92016

Is it by-name parameter you are after? If so, your syntax is a bit off. Here is the correct way:

scala> class Wow
defined class Wow

scala> val wows = collection.mutable.Buffer.empty[Wow]
wows: scala.collection.mutable.Buffer[Wow] = ArrayBuffer()

scala> def yo(f: => Wow) { wows += f }
yo: (f: => Wow)Unit

Upvotes: 4

Related Questions