Search code examples
scalafunctionanonymous-functionhigher-order-functions

Hello I am new to Scala, I have a question about an anonymous function problem


How this function returns "hello there"? There is definitely something that I am missing here but I don't see it

def saySomething(prefix: String) = (s: String) => {  
prefix + " " + s
} 

def saySomethingElse = saySomething("hello")

print(saySomethingElse("there"))

I tried tracing how "hello" is substituted by prefix since its the first string being passed in the function "saySomething" but then I don't understand how "there" is attached to the result.

Any help is appreciated


Solution

  • Breaking it down, it works like this:

    def saySomething(prefix: String) = (s: String) => {  
      prefix + " " + s
    } 
    

    This is a function called saySomething that returns a value:

    def saySomething(prefix: String) = ???
    

    The value it returns is an anonymous function:

    (s: String) => { prefix + " " + s } 
    

    Each time you call saySomething(prefix: String), a new function is created and the value of prefix is remembered by that new function. So when you call saySomething("hello") it remembers "hello" and returns this.

    (s: String) => { "hello" + " " + s } 
    def saySomethingElse = (s: String) => { "hello" + " " + s } 
    

    When you call that new function, you get the final string:

    saySomethingElse("there")
    // == ((s: String) => { "hello" + " " + s })("there")
    // == "hello" + " " + "there"
    

    You could call it with a different value and get a different result:

    saySomethingElse("Dolly")
    // == ((s: String) => { "hello" + " " + s })("Dolly")
    // == "hello" + " " + "Dolly"
    

    Note that saySomethingElse can just be a val not a def. It is just a variable that contains a function, it doesn't need to be a function itself.