https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

smit01

06/11/2022, 8:58 AM
Can someone give a simple code example of builder inference in new kotlin 1.7.0 version. I tried to go through docs but didn't quite understand please.😅
e

ephemient

06/11/2022, 12:05 PM
Copy code
interface BuilderScope<T> {
    fun emit(value: T)
}
fun <T> build(builder: BuilderScope<T>.() -> Unit)

build { emit(0) }
in Kotlin 1.2: does not typecheck, you need to write
build<Int> { emit(0) }
explicitly in Kotlin 1.3: does not typecheck, but it will if the function is declared
fun <T> build(@BuilderInference builder: BuilderScope<T>.() -> Unit)
In Kotlin 1.7: will typecheck as written above
🙏 1
the standard builders (
buildList
,
buildSet
,
buildMap
,
sequence
, etc.) all have a return type involving
T
, so another way to get it to typecheck is to put it in some context where the return type doesn't need to be inferred, e.g.
Copy code
val foo: List<Int> = buildList { add(0) }
but without builder inference, Kotlin cannot infer the type if
Int
does not appear anywhere
🙏 1
4 Views