在Scala中指定Lambda返回类型 [英] Specifying the lambda return type in Scala

查看:100
本文介绍了在Scala中指定Lambda返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这是一个理论问题,我不是在试图解决任何问题,也不是为了实际目的而试图达到任何效果

使用(arguments)=>expression语法在Scala中创建lambda时,可以显式提供返回类型吗?

Lambda与方法没有什么不同,它们都被指定为表达式,但是据我所知,方法的返回类型很容易用def name(arguments): return type = expression语法定义.

考虑以下(说明性)示例:

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

解决方案

您始终可以通过附加:和类型来声明表达式的类型.因此,例如:

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

例如,如果您有一个复杂的大型表达式,并且不想依靠类型推断来使这些类型变得直截了当,那么这很有用.

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

但是,如果将结果分配给具有指定类型的临时变量,则可能更加清楚:

val fn: Int => Option[Bar] = {
  if (foo(y)) x => Some(bar(x))
  else        _ => None
}

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

解决方案

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
}

这篇关于在Scala中指定Lambda返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆