简体   繁体   English

有没有办法指定Scala函数文字的返回类型?

[英]Is there a way to specify the return type of an Scala function literal?

I was wondering if it is possible to specify the return type of a function literal. 我想知道是否可以指定函数文字的返回类型。 For example I have 比如我有

(x:Int) => x * 2 // scala infers the type Int => Int
((x:Int) => Double) => x * 2 // does NOT compile

I know that Scala will do type inference to find the return type but I would like to explicitly specify the type so that the compiler catches the error earlier. 我知道Scala会进行类型推断以找到返回类型,但我想明确指定类型,以便编译器更早地捕获错误。

Of course I can force the check by 当然,我可以强制检查

val a: Int => Int = (x: Int) => x * 2

But is it possible to specify on a function literal directly? 但是可以直接在函数文字上指定吗?

"Specifying the type" is called type ascription . “指定类型”称为类型归属 So if the function literal should be of type Int => Double (take one Int parameter and return a Double) then you could specify it like this: 因此,如果函数文字应该是Int => Double类型(取一个Int参数并返回一个Double),那么您可以像这样指定它:

 (x: Int) => { x * 2.0 }:Double

As mentioned Scala does type inference so the type ascription is not really needed, but if you want to "hint" the type checker about the intended type you can do it. 正如前面提到的那样,Scala会进行类型推断,因此不需要类型归属,但是如果你想“提示”关于预期类型的​​类型检查器,你可以这样做。 But as mentioned in the documentation type ascription is not commonly used. 但正如文档类型中提到的那样,归档并不常用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM