dimsuz
05/15/2021, 12:07 PMclass Builder {
fun <R> build(action: (R) -> R): Builder = this
}
fun main() {
val value = 3
Builder()
.build { value } // compiler error: not enough information to infer type variable R
}
That is: lambda is returning Int
therefore R
is Int
UPD: this is kotlin 1.5.0Ivan Krylov
05/15/2021, 3:09 PMdimsuz
05/15/2021, 3:54 PMInt
. that's kotlin's default, it has no ambiguity in this case. If I add val value: Int = 3
it highlights : Int
as "redundant" and the error still stays. Even if I replace int with string, or whatever other type, it stays, so that's not it.russhwolf
05/15/2021, 5:48 PMaction
to be () -> R
or if you do Builder().build { _: Int -> value }
dimsuz
05/15/2021, 6:29 PMfun <R> build(action: (R) -> R) = Unit
fun main() {
val value: Int = 3
build { value } // not enough information to infer type variable R
}
But here's an equivalent Haskell program and it compiles and runs perfectly. So it seems like a type inference limitation...
build :: (a -> a) -> ()
build action = ()
main = do
let value = 3
return $ build (\_ -> value)
ephemient
05/15/2021, 6:37 PMlhwdev
05/16/2021, 6:07 AM.build<Int> { value }
looks cleaner to me.
There is BuilderInference
, but I don't know if it can be applied here; afaik it infers type from value arguments.ephemient
05/16/2021, 7:02 AM.build { _: Int -> value }
is sometimes preferable if there are multiple type parameters and you only need to hint a single one (because <>
forces you to write all of them)dimsuz
05/16/2021, 3:17 PMephemient
05/16/2021, 6:06 PMdimsuz
05/17/2021, 12:45 PM