Skip to content

Instantly share code, notes, and snippets.

@volodymyrprokopyuk
Created January 22, 2018 10:13
Show Gist options
  • Save volodymyrprokopyuk/12f81c9d890d5d0dd3188a3b487cacad to your computer and use it in GitHub Desktop.
Save volodymyrprokopyuk/12f81c9d890d5d0dd3188a3b487cacad to your computer and use it in GitHub Desktop.
Kotlin let, also, run, apply
package org.vld.kotlin.language
class Demo(private val property: String = "Demo") {
fun runExample() {
// run > transformation function > this > returns new value
val string = "run Kotlin".run {
println(this)
"run Kotlin 1.2.20"
}
println(string)
}
fun letExample() {
// let > transformation function > it + outer this > returns new value
val string = "let Kotlin".let {
println("let ${this.property}")
println(it)
"let Kotlin 1.2.20"
}
println(string)
}
fun applyExample() {
// apply > mutating operation > this > returns original object
val string = "apply Kotlin".apply {
println(this)
}
println(string)
}
fun alsoExample() {
// also > mutating operation > it + outer this > returns original object
val string = "also Kotlin".also {
println("also ${this.property}")
println(it)
}
println(string)
}
}
fun main(args: Array<String>) {
val demo = Demo()
with(demo) {
runExample()
// run Kotlin
// run Kotlin 1.2.20
letExample()
// let Demo
// let Kotlin
// let Kotlin 1.2.20
applyExample()
// apply Kotlin
// apply Kotlin
alsoExample()
// also Demo
// also Kotlin
// also Kotlin
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment