1

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?

3 Answers 3

6

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 
Sign up to request clarification or add additional context in comments.

1 Comment

A good rule of thumb is to require parens when the computation involves a side-effect, but don't require them when the computation is pure. I guess you could use parens this way in the same way that Lisp and Ruby use !.
2

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.

Comments

2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.