https://kotlinlang.org logo
Title
i

iex

05/16/2019, 7:36 PM
val closure = { (a: Int -> Int) ->
    a * 2
}
l

louiscad

05/16/2019, 7:37 PM
You can't. You can specify the type of
closure
explicitly though, and the IDE can even do that for you with an intention (alt/option + enter)
i

iex

05/16/2019, 7:38 PM
😕 type inference is failing
l

louiscad

05/16/2019, 7:38 PM
? Can you tell more details?
s

Shawn

05/16/2019, 7:39 PM
val closure: (Int) -> Int = { a -> a * 2 }
is the closest you can get to what you’re asking for, I think
e

elizarov

05/16/2019, 7:39 PM
Expected type is one way. You can also use anonymous function literal instead:
val closure = fun(a: Int): Int { ... }
s

streetsofboston

05/16/2019, 7:40 PM
@iex What is the type of
closure
if you would provide it explicitly?
You could end your last expression in your lambda with `as MyReturnType`….
E.g.
val closure = { a: Int -> (a + 5) as Number }
Is this what you try to accomplish?
i

iex

05/16/2019, 7:46 PM
yeah but I prefer to avoid casting, even in this case
managed to solve it with an extension function
s

streetsofboston

05/16/2019, 7:47 PM
Now i’m curious … 🙂
i

iex

05/16/2019, 7:47 PM
it's a bit too custom to post it I think...
declaring a local variable with the correct type and returning it also solved it, but that was 2 lines of code 😄
s

streetsofboston

05/16/2019, 7:48 PM
Providing the type explicitly is probably less typing … 🙂
i

iex

05/16/2019, 7:49 PM
that's basically what I'm doing with the extension
have a chain of map and flatmap which seemed to confuse the compiler
s

streetsofboston

05/16/2019, 7:51 PM
It could be that the new type inference system, that is still a bit in flux, may help with that.

https://www.youtube.com/watch?v=MyljSWm0Y_k

(fast forward to the type inference section)
i

iex

05/16/2019, 7:53 PM
thanks, will watch it later 👍