Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the lambda return type in Scala

Note: this is a theoretical question, I am not trying to fix anything, nor am I trying to achieve any effect for a practical purpose

When creating a lambda in Scala using the (arguments)=>expression syntax, can the return type be explicitly provided?

Lambdas are no different than methods on that they both are specified as expressions, but as far as I understand it, the return type of methods is defined easily with the def name(arguments): return type = expression syntax.

Consider this (illustrative) example:

def sequence(start: Int, next: Int=>Int): ()=>Int = {
    var x: Int = start

    //How can I denote that this function should return an integer?    
    () => {
        var result: Int = x
        x = next(x)
        result
    }
}
like image 399
corazza Avatar asked Mar 10 '14 23:03

corazza


1 Answers

You can always declare the type of an expression by appending : and the type. So, for instance:

((x: Int) => x.toString): (Int => String)

This is useful if you, for instance, have a big complicated expression and you don't want to rely upon type inference to get the types straight.

{
  if (foo(y)) x => Some(bar(x))
  else        x => None
}: (Int => Option[Bar])
// Without type ascription, need (x: Int)

But it's probably even clearer if you assign the result to a temporary variable with a specified type:

val fn: Int => Option[Bar] = {
  if (foo(y)) x => Some(bar(x))
  else        _ => None
}
like image 152
Rex Kerr Avatar answered Sep 23 '22 05:09

Rex Kerr