null
In Java, NullPointerException is common to our developers, which brings us too many unnecessary troubles. Kotlin has improved it. Kotlin makes more null problems that may occur during runtime, and forces us to pay attention to them in advance during the compilation period in the way of compiling and reporting errors, rather than waiting for the running to report errors to prevent them, It improves the robustness of the program.
For the null value problem, Kotlin does the opposite. Unless otherwise specified, variables are not allowed to be null. In this way, the runtime crash caused by the null problem is solved from the root.
If we assign null to the variable, the compiler will prompt us in red to modify the code.
Nullability
In order to avoid null pointer exceptions, Kotlin does not let us assign null values to non null type variables, but null still exists in Kotlin.
fun main() { // ? The meaning here is to indicate that the declared str is an nullable string var str: String? = "honey" str = null println("input:$str") }
Kotlin distinguishes nullable types from non nullable types, so it is necessary to run nullable type variables, which may be null values. The compiler is always vigilant against this potential risk. In order to deal with this risk, kotlin does not allow us to call functions with nullable type variables unless we actively take over security management.
Safe call operator '?.'
"." will tell the compiler to skip the function call instead of returning null if it is a null value.
str = null val newStr = str?.capitalize() println(newStr)
From the following example, we do see that when the value is null, the function call will be skipped:
fun main() { val str = null println(str?.capitalized()) } private fun String.capitalized(): String { println("I was called") return if (isNotEmpty() && this[0].isLowerCase()) substring(0, 1).toUpperCase() + substring(1) else "String is null" }
Security operator "let"
Safe calling allows us to call functions with nullable type values, but we also want to do some additional things, such as assigning new values when the variable is a blank string, or calling other functions when it is not a blank string. At this time, let should perform.
fun main() { var str: String? = "honey" //var str: String? = null / / when it is null, calling the let function safely will skip directly //str = "" str = str?.let { if (it.isNotBlank()) { it.capitalize() } else { "str is blank" } } println("str = $str") }
Security operation caller "!!!"
"!." is a non empty assertion operator, also known as an exclamation point operator. It will be thrown when the caller is null KotlinNullPointerException.
fun main() { var str: String? = "" str = null str!!.capitalize() }
The above code will run null pointer exception:
Safe call operator VS if
We can also use if to judge the null value as in Java, but in contrast, the safe call operator is more flexible and the code is more concise. We can use the safe operator to make chain calls to multiple functions.
fun main() { var str: String? = "luffy" //str = null //Use if judgment if(str != null) str = str.capitalize() else str = "str is null" println("str = $str") //Chained calls using secure call operators println(str?.capitalize().plus(" is great.")) }
Empty merge operator
The "?:" operator is used to use the result value on the right if the evaluation result of the expression on the left is null. Otherwise, the result value on the left is used.
fun main() { var str: String? = "luffy" str = null println(str ?: "honey") }
The empty merge operator can also be used in combination with the let function instead of if/else:
fun main() { var str: String? = "luffy" str = null str = str?.let { it.capitalize() } ?: "Honey" println(str) }
abnormal
import kotlin.IllegalArgumentException fun main() { var str: String? = null try { checkOperation(str) str!!.capitalize() } catch (e: KotlinNullPointerException) { println(e.cause?.message) } } fun checkOperation(str: String?) { str ?: throw UnskilledException() } /** * Custom exception * PS:Kotlin The IllegalArgumentException in is the alias of IllegalArgumentException under the java.lang package * @SinceKotlin("1.1") public actual typealias IllegalArgumentException = java.lang.IllegalArgumentException */ class UnskilledException() : IllegalArgumentException("Improper operation")
Prerequisite function
The Kotlin standard library provides some convenience functions. These built-in functions can throw exceptions with custom information. These convenience functions are called prerequisite functions. We can use them to define preconditions. The conditions must be met before the object code can be executed.
fun main() { var num: Int? = null try { checkNotNull(num){"Improper operation"} num!!.plus(1) } catch (e: KotlinNullPointerException) { println(e.cause?.message) } }
String operation
substring
String interception. The substring function supports parameters of intran type (representing an integer range). The range created by until does not include the upper limit value.
const val WORDS = "Luffy's friend" fun main() { val index = WORDS.indexOf('\'') var str1 = WORDS.substring(0, index) //In Kotlin, substring function supports intran type var str2 = WORDS.substring(0 until index) println("str1 = $str1") println("str2 = $str2") }
split
The split function returns the List set data. The List set supports deconstruction syntax. It allows us to assign values to multiple variables in one expression. Deconstruction is often used to simplify the assignment of variables.
const val NAMES = "Luffy,Honey,Kitty" fun main() { val names: List<String> = NAMES.split(',') println(names[0]) //Deconstructive grammatical features val (origin, dest, proxy) = NAMES.split(',') println("$origin,$dest,$proxy") }