Created
March 21, 2020 14:32
-
-
Save bseib/7be7cfe6a09d264432fa2e59b48bc3d5 to your computer and use it in GitHub Desktop.
Kotin Scope Function Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
println("--- let ---") | |
//yo().let { println(this) } // compile error | |
yo().let { println(it) } // AAA(greeting=hello) | |
println(yo().let { it.greeting + " world" }) // hello world | |
println("\n--- run ---") | |
yo().run { println(this) } // AAA(greeting=hello) | |
yo().run { println(greeting.length) } // 5 | |
println(yo().run { "high " + greeting.length }) // high 5 | |
println("\n--- also ---") | |
//yo().also { println(this) } // compile error | |
yo().also { println(it) } // AAA(greeting=hello) | |
println(yo().also { it.greeting + " world" }) // AAA(greeting=hello) | |
println("\n--- apply ---") | |
yo().apply { println(this) } // AAA(greeting=hello) | |
yo().apply { println(greeting.length) } // 5 | |
println(yo().apply { "high " + greeting.length }) // AAA(greeting=hello) | |
println("\n--- with ---") | |
with(yo()) { println(this) } // AAA(greeting=hello) | |
with(yo()) { println(greeting.length) } // 5 | |
println(with(yo()) { "high " + greeting.length }) // high 5 | |
} | |
fun yo(): AAA { | |
return AAA(greeting = "hello") | |
} | |
data class AAA(val greeting: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment