Here’s a puzzler for scala fans: What will be the console output of the following program:

def foo1() {
	println("> foo1()")
	return "foo1"

def foo2() {
	println("> foo2()")

def foo3() = {
	println("> foo3()")

def foo4():String {
	println("> foo4()")


Look carefully at each of the def lines, and write down what you think the output will be.

Okay, so it’s a trick question. It won’t actually compile, because the definition of foo4() is invalid, despite the fact that it looks (to my eyes) the same as foo1 and foo2, with the optional return type filled in. Let’s comment that out (and also the call to it). Now what will it print?

The answer is:

> foo1()
> foo2()
> foo3()

What the hell, scala?

It should not be possible to write a function body that executes, has a return statement, and yet returns Unit (scala’s void type). Yes, it is my fault for leaving off the (completely unnecessary, imho) = symbol when defining a function, but this is something I do a lot, and I would like the compiler to yell at me loudly and angrily whenever I do something so foolish. I wasted an entire afternoon debugging an actual instance of this, and it sucks.

I still don’t actually know why the code in foo1 and foo2 executes but doesn’t return a value, can anyone enlighten me? I thought = was mandatory, so I would expect them to be compile errors. But they’re clearly doing something else entirely.