Scala Lambda Example

Lambdas are just anonymous functions, although typically they are expected to be side-effect free (more of a calculus-style function that does a computation)

For instance, in Javascript you might do this:

function x() {
}

...or....

var y = function() { }

The equivalent in Scala might be:

val y = () => {}
 
y()
y: () => Unit = 

So you can see the type it returns is “Unit” which appears approximately equivalent to “void”, however unlike “void” in Java you can declare things as Unit (although with only a single value):

val x: Unit = ()

Whether this is useful is questionable.

You could, for instance make a lambda that doubles a value, and use it like so (the forms listed are all equivalent):

val y = (x: Int) => x * 2

List(1, 2, 3).map(y)
List(1, 2, 3) map y
List(1, 2, 3).map((x: Int) => x * 2)

All returning:

res11: List[Int] = List(2, 4, 6)

There isn’t a way to make the lambda type-less (or generic):

val y = (x) => x

:8: error: missing parameter type
       val y = (x) => x

That said, you can cheat this a couple ways, either with Any (most similar to void* in C):

val y = (x: Any) => x

y: Any => Any = 

Or, instead of making a lambda, make a method (T being a generic type here):

def y[T] = (x: T) => x 

Which does actually work:

y: [T]=> T => T

scala> y(1)
res7: Int = 1

This is basically defining a method in some object (less obvious if you’re typing the Scala REPL), although it might otherwise behave similarly to lamdbas. This is familiar, in that it is similar to methods in Java.

In the shorter lambdas, the lack of a “return” feels very natural, but as these get longer it starts to feel weird. This is especially true if the code gets longer – when there are multiple statements, the result of the last one is implicitly returned (when writing code, it can be helpful to define the return type of the function, so you get an error if you accidentally return the wrong thing)

You should resist the temptation to add “return” to your functions. The authors of Scala made the questionable decision to change the traditional meaning of return, such that it takes you out of all lambdas, and up out of the most recent method on the stack – which is likely quite a ways up, and not at all what you’d expect.