String template
Kotlin allows strings to contain embedded expressions beginning with “$”.
In Java we might need a definition like this to concatenate strings:
String message = "n = " + n;
Copy the code
But in Kotlin, we can just use the “$” concatenation:
val message = "n = $n"
Copy the code
Obviously, using string templates can improve our development efficiency.
Conditional expression
This is a normal conditional statement.
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
Copy the code
In Kotlin, an if expression has a return value, so it can be expressed as follows:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
Copy the code
About Air Safety
Null security is a major feature of Kotlin. In Java, NPE (NullPointerException) is a regular feature, but in Kotlin, we will see NPE.
For nullable variables, we must use “?” Declare it specifically as a variable with a null value:
var b: String? = "abc"
Copy the code
Normal use is like this
var b: String = "abc"
Copy the code
We get an error if we call b directly
val l = b.length()
Copy the code
So, how do we use nullable variables?
Can we use security operators? “” .” to make a method call Like this:
b? .length()Copy the code
If b is null, return null; Otherwise, call b.length().
Why use the null-safety operator?
This allows us to solve the problem of nulling, and “! = null “say goodbye forever, and empty safes can be nice in chained calls.
bob? .department?.head?.nameCopy the code
Security transformation
In Java, a ClassCastException occurs when a type conversion error occurs, whereas in Kotlin, you can safely cast “as?” To avoid this problem.
val aInt: Int? = a as? Int
Copy the code
If the conversion fails, null is returned, otherwise correct data is returned.
Type checking
In Java, we can verify a type with “instanceof”, in Kotlin, we can use “is”
fun getStringLength(obj: Any): Int? {
if (obj is String) {
return obj.length
}
return null
}
Copy the code
A collection of
In Kotlin, you can iterate over a collection using the IN operator.
for (item in items) {
println(item)
}
Copy the code
Kotlin prefers lambda to filter collections;
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
Copy the code
The for loop
In Kotlin, the for loop is iterated using the in keyword.
val items = listOf("apple"."banana"."kiwi")
for (item in items) {
println(item)
}
Copy the code
The while loop
This is a simple example of a while loop
val items = listOf("apple"."banana"."kiwi")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
Copy the code
When the expression
A simple example of using the When expression instead of the Switch statement in Kotlin is as follows:
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
Copy the code