RubenLaguna
RubenLaguna

Reputation: 24696

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?

Upvotes: 4

Views: 565

Answers (1)

RubenLaguna
RubenLaguna

Reputation: 24696

"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.

Upvotes: 3

Related Questions