guy mograbi
guy mograbi

Reputation: 28598

Scala Anonymous Function - does not behave as I expected

I am a scala newbie.

I would like to understand why this code does not behave as I expect it

def invokeFunc( myFunc: () => String ){
    println(myFunc())
  }

  def callInvoker(){
     invokeFunc({ return "this is a string" })
  }

When I invoke "callInvoker" I get nothing. I expected a print for "this is a string", but instead nothing returns. Why?

Upvotes: 1

Views: 164

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

This is because return does not return from your anonymous function, but from the enclosing method. So when doing invokeFunc({ return "this is a string" }) you are effectively returning from callInvoker (with the value "this is a string", which is just discarded as callInvoker is of type Unit).

A corrected code would be:

def invokeFunc( myFunc: () => String ){
  println(myFunc())
}

def callInvoker(){
   invokeFunc{() => "this is a string" }
}

callInvoker()

Now your anonymous function actually returns "this is a string" (any function/method returns its last expression, unless an explicit return is encountered, but as I explained return applies to the enclosing method and never to an anonymous function).

Upvotes: 4

Related Questions