This is the eleventh part of the video series on Kotlin language.
Read and watch the other parts here.
1. | Hello Kotlin |
2. | Declaring Variables |
3. | Data Types |
4. | String (Part 1) |
5. | String (Part 1) |
6. | Conditional Expressions |
7. | Functions (Part I) |
8. | Functions (Part II) |
9. | Lambda |
10. | Range |
We discuss null safety in Kotlin language. Kotlin treats nullable and non-nullable references differently. ie., You cannot assign null to references. Compiler doesn’t like it. If you have a reference that can accept null value too, then the question-mark(?) comes into picture. Null comparisons have also been made simple thanks to Elvis operator (?:)
The examples used in the video are given below
fun main(args:Array<String>){ var name:String = "Ram" //name = null //This condition is always true if(name != null){ println(name) } var anotherName:String? = "John" if(anotherName != null){ println(anotherName) } anotherName = null println(anotherName) println(anotherName?.length ?: -1) }
Nullable types can be passed to functions and also returned as output
fun calculateLength(value:String?):Int?{ return value?.length } fun main(args:Array<String>){ println(calculateLength("Joe")) println(calculateLength(null)) }
You can find the video here.