在Scala中指定Lambda返回类型 [英] Specifying the lambda return type in Scala
问题描述
注意:这是一个理论问题,我不是在试图解决任何问题,也不是为了实际目的而试图达到任何效果
使用(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屋!