chen
chen

Reputation: 4490

Unit as parameter

What is the following methods' difference?

def sum1() = 1+2

def sum2(a:Unit) = 1+2

I think they are semantically identical, is it right?

Upvotes: 1

Views: 146

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

These methods are not identical. Once receives a parameter, the other does not. See here:

scala> sum1(println("Hi, there!"))
<console>:9: error: too many arguments for method sum1: ()Int
              sum1(println("Hi, there!"))
                  ^

scala> sum2(println("Hi, there!"))
Hi, there!
res1: Int = 3

Upvotes: 2

Don Stewart
Don Stewart

Reputation: 137937

Note that passing unit as an argument to an expression lets you simulate lazy evaluation in a strict language. By "moving evaluation under a lambda" you ensure that the expression isn't eval'd until the () gets passed in. This can be useful for e.g. auto-memoizing data structures, which collapse from a function to a value the first time they're inspected.

Upvotes: 2

Dylan
Dylan

Reputation: 13859

With sum1, you can call it with or without parentheses:

val x = sum1    // x: Int = 3
val y = sum1()  // y: Int = 3

But with sum2 you are forced to provide parentheses.. I think that if you call sum2(), you are actually calling sum2 with () as the argument a.

val x2 = sum2   // error
val y2 = sum2() // y2: Int = 3

Upvotes: 6

Related Questions