@rkenmi - Scala Anonymous Functions

Scala Anonymous Functions


Scala Anonymous Functions


Back to Top

Updated on June 10, 2017

Material: https://class.coursera.org/progfun-005/

type is basically an alias. It allows for neater code, and simplified readability. Since we can have function types, the code can get really messy when left raw.

For example:

def justTrue(iB : Int => Boolean) : Int => Boolean = (x : Int) => true

The syntax looks overly complicated. The function justTrue takes in a function iB as a parameter. iB takes in a single parameter, which would be an Int, and iB returns a Boolean, hence Int => Boolean. However, justTrue doesn't even call iB, even though iB is passed into it. justTrue snatches the Int parameter from iB, and then calls an anonymous function which takes that Int and returns a true.

By making use of type:

type Set = Int => Boolean

We can reduce the definition of justTrue to:

def justTrue(iB : Set) : Set = (x : Int) => true

Much better! And why does this work? Since we are taking an Int x which comes from iB, we are automatically returning a function. Since justTrue is of type Set, we know that this is equivalently Int => Boolean. Therefore, the function that needs to be returned, must be of the format Int => Boolean or simply a Set. {(x: Int) => true} is an anonymous function, so justTrue will run justFine.

Examples of returning Sets, or by type:
def justNumber(iB : Set) : Set = Set(100) or def justNumber(iB : Set) : Set = Set(5)


Article Tags:
Scalaanonymous function