简体   繁体   中英

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.

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:

 (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. But as mentioned in the documentation type ascription is not commonly used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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