Reputation: 2883
Am bogged down by this syntax:
def foreach(f: Tweet => Unit): Unit = {
f(elem)
left.foreach(f)
right.foreach(f)
}
where Tweet
is a class with three variables. What does it mean for a function to return Unit
? I tried different things but am not able to call the function itself in this case.
Please help. Thanks
Upvotes: 6
Views: 2108
Reputation: 84
To return Unit means the function returns nothing. In other words, you are calling the function for its side-effects rather than for anything it calculates for you.
Given your foreach example, here are some functions that might make sense.
// A Tweet class with 3 values (shorter declaration than vars).
case class Tweet( a: Int, b: String, c: String )
// Print out the contents of a Tweet.
def tweetFunc( t: Tweet ): Unit = {
println( "I am a Tweet. %d %s %s".format( t.a, t.b, t.c ) )
}
// The data that is used by the foreach function.
val elem = Tweet( 1, "Hello", "World" )
val left = List( elem, Tweet( 2, "a", "b" ) )
val right = List( Tweet( 3, "c", "d" ) )
// Original foreach function.
def foreach(f: Tweet => Unit): Unit = {
f(elem)
left.foreach(f)
right.foreach(f)
}
// Call the foreach function with tweetFunc as the parameter.
foreach( tweetFunc _ )
///// OUTPUT /////
I am a Tweet. 1 Hello World // from f(elem)
I am a Tweet. 1 Hello World // from left.foreach(f)
I am a Tweet. 2 a b // from left.foreach(f)
I am a Tweet. 3 c d // from right.foreach(f)
Upvotes: 5
Reputation: 62835
Unit in scala is identical to void in Java, moreover, Java sees Scala's Unit as void, and vise versa. So in java it could be written like:
void foreach(MethodThatReturnsVoid f) {
f.apply(elem)
left.foreach(f)
right.foreach(f)
}
It is a little bit pseudocode (since java doesn't support first class functions yet) but I hope you've got the idea.
Upvotes: 5
Reputation: 2345
The definition of Unit is mentioned here: http://www.scala-lang.org/api/current/index.html#scala.Unit
It is not exactly identical to void in java because it is a subtype and not a reserved word. This design is better, since void
is now treated as a first class type like other types. Since your code has all the types defined explicitly, you can see Unit can be substituted with another type and the syntax is still correct. Alternatively, Unit can always be substituted with {} or inferred. In a definition with no return value, this can be written like the following.
def foreach(f: Tweet => Unit) { ... }
Upvotes: 1