Also known as anonymous functions. This is a special type of functions that I have not seen like this in any other language, but I’m sure its there somewhere.
It’s a function that can take a number of parameters and directly produce an output.
The most common example would be:
scala> (x: Int) => x * 2
Or with two or more parameters:
scala> (x: Int, y:Iny) => x * y
Or you could create it completely without parameters:
scala> () => println("Now that is a cool function")
Now this does not do you a lot of good if you cannot call the function but all of these examples do actually run… I guess. No-one actually knows because they will not be called. If you make an anonymous function in the woods and no-one calls it does it run. I’ll bee thinking about that all night. ANYWAYS: You could assign it to a variable as so:
scala> var printCoolFunction = () => println("Now that is a cool function")
var printCoolFunction: () => Unit = Lambda$1399/0x000000080079a040@7507d96c
scala> printCoolFunction()
Now that is a cool function
This is basically the same as a primitive method but it can be useful sometimes. The cool part however comes when we start passing the anonymous functions as parameters:
scala> val GPA = List(6,7,5,6,7,8,5,4,5)
val GPA: List[Int] = List(6, 7, 5, 6, 7, 8, 5, 4, 5)
scala> GPA.foreach((x: Int) => println(x * 2))
12
14
10
12
14
16
10
8
10
Now this is pretty cool. Lets try that with another example:
scala> val GPA = List((6,"Jakob"),(10, "Leo"), (9, "Muffi"), (2, "Frode"), (5, "Ninka"), (7, "Rasmus"))
val GPA: List[(Int, String)] = List((6,Jakob), (10,Leo), (9,Muffi), (2,Frode), (5,Ninka), (7,Rasmus))
scala> val studentsWithTopGrades = GPA.filter((x: Int,name:String) => x>7)
val studentsWithTopGrades: List[(Int, String)] = List((10,Leo), (9,Muffi))
Now this is where the true power is. We just took a full list of good students and their grades point average (fyi: actually they are not real students) and in one line filtered the ones with a GPA above 7. This can be shortened to:
scala> val studentsWithTopGrades = GPA.filter((x,_) => x>7)
Using placeholders. A last typical way of using it is using the map:
scala> val GPA = List(6,7,5,6,7,8,5,4,5)
val GPA: List[Int] = List(6, 7, 5, 6, 7, 8, 5, 4, 5)
scala> val newGPA = GPA.map(_*1.01)
val newGPA: List[Double] = List(6.0600000000000005, 7.07, 5.05, 6.0600000000000005, 7.07, 8.08, 5.05, 4.04, 5.05)
Here we have made a newGPA which is just slightly higher. And because we only have one type in the list we can omit most of the anonymous function and replace it with a placeholder. This is pretty cool in my book.