Specifying the lambda return type in Scala

2019-04-06 16:04发布

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
    }
}

3条回答
Rolldiameter
2楼-- · 2019-04-06 16:24
x => x:SomeType

Did not know the answer myself as I never had the need for it, but my gut feeling was that this will work. And trying it in a worksheet confirmed it.

Edit: I provided this answer before there was an example above. It is true that this is not needed in the concrete example. But in rare cases where you'd need it, the syntax I showed will work.

查看更多
不美不萌又怎样
3楼-- · 2019-04-06 16:28

Let say you have this function:

def mulF(a: Int, b: Int): Long = {
      a.toLong * b
}

The same function can be written as lambda with defined input and output types:

val mulLambda: (Int, Int) => Long = (x: Int, y: Int) => { x.toLong * y }
查看更多
你好瞎i
4楼-- · 2019-04-06 16:45

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
}
查看更多
登录 后发表回答