val alice = Person("Alice", 20, "Amsterdam")
println(alice)
alice.moveTo("London")
alice.incrementAge()
println(alice)
Person("Alice", 20, "Amsterdam").run {
println(this)
moveTo("London")
incrementAge()
println(this)
}
Person("Adam").apply {
age = 32
city = "London"
}
run {
val digits = "0-9"
val hexDigits = "A-Fa-f"
val sign = "+-"
Regex("[$sign]?[$digits$hexDigits]+")
}
Person("Adam").apply {
age = 20
city = "London"
}
Random.nextInt(100).also {
writeToLog("getRandomInt() generated value $it")
}
fun getRandomInt(): Int {
return Random.nextInt(100).also {
writeToLog("getRandomInt() generated value $it")
}
}
val countEndsWithE = numbers.run {
add("four")
add("five")
count { it.endsWith("e") }
}
Function | Object reference | Return value | Is extension function |
---|---|---|---|
let | it | Lambda result | Yes |
run | this | Lambda result | Yes |
run | - | Lambda result | No: called without the context object |
with | this | Lambda result | No: takes the context object as an argument. |
apply | this | Context object | Yes |
also | it | Context object | Yes |
var str = "Hello World"
str.let { println("$it!!") }
fragmentManager?.let {
tagFragment.show(it, "")
}
var tutorial = "This is Kotlin Tutorial"
println(tutorial) //This is Kotlin Tutorial
tutorial = run {
val tutorial = "This is run function"
tutorial
}
println(tutorial) //This is run function
webView.settings.run {
javaScriptEnabled = true
domStorageEnabled = true
userAgentString = "mobile_app_webview"
webView
}
data class Person(var name: String, var tutorial : String)
var person = Person("Anupam", "Kotlin")
with(person){
name = "No Name"
tutorial = "Kotlin tutorials"
}
val p = person.apply{
name = nameInput.text.toString()
phone = phoneInput.text.toString()
id = idInput.text.toString()
sex = sexInput.text.toString()
}
val numbers = mutableListOf("one", "two", "three")
numbers
.also { println("The list elements before adding new one: $it") }
.add("four")
.also { println("The list elements after adding new one: $it") }