简体   繁体   中英

Why can't I specify a result type for an anonymous function in Scala?

Edit: Found the answer, see end of post.

kept getting errors, found it was because I was trying to add result types to lambdas. This is fine

(p: Int) => p

whereas

(p: Int): Int => p

causes it complaints. I'm surprised - why not allow it? After all I can specify a type in the variable (I've bracketed the type for readability) if I assign the lambda:

val f2: (Int => Int) = (p: Int) => p

but then I might as well def it:

def f2(p: Int): Int = p

I can't see any obvious harm in disallowing it, but it is unexpected. Thoughts?


Edit: Stone me, you can:

(p: Int) => p : Int

OK, answered. Never seen that before. I guess I'll leave this here for posterity.

Per suggestion of 0__, the answer is to suffix the body of the lambda with the type, not put it after the parameter list as would be suggested by the def syntax.

Actual example I was using, to destructure a list and return a tuple of the first 2 items:

(p: List[Int]): Tuple2[Int, Int] => { val x :: y :: rest = p; (x, y) }

fails, but this succeeds

(p: List[Int]) => { val x :: y :: rest = p; (x, y) }: Tuple2[Int, Int]

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