Back to Blog
Kotlin is null6/20/2023 In below case, if b is null, it will through Null pointer exception. Val name = node.getName() ?: throw IllegalArgumentException("name expected") Val parent = node.getParent() ?: return null Note that the right-hand side expression is evaluated only if the left-hand side is null. If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. When we have a nullable reference b, we can say “if b is not null, use it, otherwise use some non-null value”: val l: Int = if (b != null) b.length else -1Ībove code can be expressed with the Elvis operator, written ?: Println(b?.length) //it returns null if the b is nullable, it will not throw Null pointer exception You can use safe call operator(?.) if you dont want to throw null pointer exception when you try to access nullable reference b val b: String? = null Kotlin provides Safe call(?.), Elvis(?:), Not-null assertion operator(!!) operators to work on nullable types. Kotlin’s type system is aimed to eliminate NullPointerException’s from our code. In Java this would be the equivalent of a NullPointerException or NPE for short. One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception.
0 Comments
Read More
Leave a Reply. |