Checks / Exit Conditions
Instead of writing something like if !condition throw …
we may use require
and check
for quick exit conditions:
val num = 1;
require(num > 1){
// ...
}
val num = 1;
require(num > 1){
// ..
}
Pluralize Strings
Adding pluralization as extension function
fun String.pluralize(count:Int):String {
return if (count > 1){
this + 's'
} else {
this
}
}
Use it like this
"user".pluralize(users.size)
Infix Operators
infix fun Int.multiplyBy(number:Int) : Int {
return this * number
}
Using the infix operator:
5 multiplyBy 4
Setting multiple Class Properties at once
data class User(var name:String, var age: Int)
val user = User("Sally", 42)
println(user)
user.apply {
name = "Sarah"
age = 44
}
println(user)
with(user){
name = "Sally"
age = 43
}
println(user)
yields:
User(name=Sally, age=42)
User(name=Sarah, age=44)
User(name=Sally, age=43)
Using let to invoce function on results of call chains
fun calcSth(): IntRange{
return (1..5)
}
calcSth().let {
println(it.contains(2))
}
// prints: true