Skip to content

Instantly share code, notes, and snippets.

@gja
Last active December 25, 2022 12:47
Show Gist options
  • Save gja/c6eae37b0da327cf03b7ba0ebc1acbc8 to your computer and use it in GitHub Desktop.
Save gja/c6eae37b0da327cf03b7ba0ebc1acbc8 to your computer and use it in GitHub Desktop.
Kotlin DSL Shadowing
data class SetFoo(val foo: Int)
data class SetFooAndBar(val foo: Int, val bar: Int)
fun setFooTo3AndBarTo42(exec: SetFooAndBar.() -> Unit) {
SetFooAndBar(3, 42).exec()
}
fun setFooTo4(exec: SetFoo.() -> Unit) {
SetFoo(4).exec()
}
fun main() {
// Adds foo and bar into scope
setFooTo3AndBarTo42 {
println("Foo is ${foo}")
println("Bar is ${bar}")
// Leaves bar as it is, but shadows foo with a new value
setFooTo4 {
println("Foo is ${foo}")
println("Bar is ${bar}")
}
// Back to the old values
println("Foo is ${foo}")
println("Bar is ${bar}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment