Skip to main content

Posts

Kotlin double exclamation operator

!! What does the !! operator do? Known by different names such as the double bang or double exclamation or NPE operator. This operator forces the compiler to know a null pointer exception in case a null value is encountered. In such cases, compiler throws a KotlinNullPointerException to be precise. It allows programmers to explicitly ask Kotlin for a NPE. Let us try to understand this by an example var msg: String? msg = null println(msg!!.length) Here, on line 3, we tell Kotlin compiler to print the value of msg.length if msg is not null; else throw a Kotlin Null pointer exception. The double bang operator is useful when we can't add any meaningful null safely in code, yet code must fail when a null value is encountered. The Kotlin null pointer exception can then be caught and handled accordingly. Although, this should be rarely used given how well Kotlin tries to eliminate NPEs.

Kotlin elvis operator ?:

?: Symbol for elvis operator is ?: The elvis operator couples with safe call operator ?. Elvis operator returns the value to it's left if value is not null, else it returns the value to it's right var foo = a ?: b Here, if a is null, b is returned. If a is not null, a is returned. Another elaborate example: var msg: String? msg = null // use elvis operator var msgLength1 = msg?.length ?: 0 // use traditional null check var msgLength2: Int if (msg != null) { msgLength2 = msg.length } else { msgLength2 = 0 } println(msgLength1) // 0 println(msgLength2) // 0 In above code snippet, calculate of msgLength1 using safe call operator and elvis operator is same as calculation of msgLength2 using traditional conditional check.

Kotlin: safe call operator ?.

?. What does the safe call operator do? Symbol for safe call operator is ?. It safely calls function or accesses property of a nullable object Returns null in case the object has null value, else calls the function or accesses property. Safe call operator can be chained and returns null if any of the object in chain. var msg: String? msg = null println(msg?.length) // prints "null" // here msg?. returns null since msg is null, // instead of accessing the .length property Chaining safe call operator println(foo?.bar?.baz?.someProp) This chain would return null if either of foo, bar or baz have null value but won't check someProp for null value!

Null safety in Kotlin

Kotlin is designed to be null safe! A null pointer exception occurs when we try to use variables that have null value. Kotlin is designed in such a way that it greatly reduces the possibility of null pointer exceptions. Variables in Kotlin can not hold a null value by default Nullable variable i.e. variables that can hold null values, needs to be explicitly defined so. Let's understand a few null safety concepts in Kotlin with these simple code snippets. Remember, how to define variables? We are going to go ahead and define a variable and try to assign null value to it. var msg: String msg = null This isn't allowed in kotlin since we didn't explicitly specify that the variable msg can contain null value. If you try to run the program, you will get an error. But sometimes, we need a variable to have null value now and then some other value later. Adding a question mark at the end of variable definition allows us to explicitly declare that this variable may c

Kotlin readLine(): getting value from a user

Reading data from user in Kotlin So far, we have seen how to declare variables and print variables back to user but how do we get input from users? Kotlin has readline() function which returns a line from standard input stream. readLine() returns String which can be converted to other types as required. Let us look at readLine() function by taking some examples: // Code: val msg = readLine() println("Your msg = $msg")   // Output: Hi Your msg = Hi Here, we ask user to enter a message and then promptly display back the same message. Getting integer or other data types from readLine() method The output returned by readLine() function is String and can be converted to other types. We will learn more about type conversion in our section on data types and conversion. In the meanwhile, here's how you can convert String returned by readLine() to an Integer. // Code: println("Enter number 1: ") val x = readLine()!!.toInt()

Kotlin println(): Printing values to console

How to print values in Kotlin? Hi guys. We saw how to to declare variables in previous post and now we want to print the values to console. To print values, we use the print or println function. println is similar to print function. It just adds a newline after printing whatever we pass to the function print functions support string interpolation which is like embedding variables in other strings. We will talk about string interpolation in our section on String s. print functions print to the standard output by default which is usually the terminate or console. Here's how to print the values to console: print("hello world") // prints "hello world" println("hello world") // prints "hello world" with a new line val PI = 3.14 println(PI) // prints "3.14" println("The value of PI = " + PI) // concatenate the variable and print it println("The value of PI = $PI") // embed variable in string and pr

Variables in Kotlin

Variables are named memory location where we can store values temporarily. As the name suggests, variables vary over time. For example: a variable can have value 3 now, and then 5 later. The var keyword is used for declaring variables in Kotlin. var x = 3 var y = 4 Kotlin also offers read only variables or values. Values do not change over time and remain constant. Declare values in Kotlin using val keyword . Kotlin throws an error if trying to reassign another value to a read only variable. val PI = 3.14 // PI is a read-only variable now // reassigning is not allowed PI = 3.1415 So far, we didn't need to specify the type of variable. Kotlin infers the type of variable from the value assigned to variable. But we can also explicitly specify the type of variable (or values). var z: Int = 3 var msg: String = "Hello World" val PI: Double = 3.1415 Can we have variables with null values? Sometimes when programming, we don't know the valu