Null safety based Kotlin interview questions and answers

Nullable Non Nullable Types

What’s Null Safety and Nullable Types in Kotlin? What is the Elvis Operator?

Kotlin puts a lot of weight behind null safety which is an approach to prevent the dreaded Null Pointer Exceptions by using nullable types which are like String?Int?Float? etc. These act as a wrapper type and can hold null values. A nullable value cannot be added to another nullable or basic type of value.

To retrieve the basic types we need to use safe calls that unwrap the Nullable Types. If on unwrapping, the value is null we can choose to ignore or use a default value instead. The Elvis Operator is used to safely unwrap the value from the Nullable.
It’s represented as ?: over the nullable type. The value on the right hand side would be used if the nullable type holds a null.


var str: String? = "JournalDev.com"
var newStr = str?: "Default Value"
str = null
newStr = str?: "Default Value"

kotlin interview questions null safety elvis operator

How is !!different from ?. in unwrapping the nullable values? Is there any other way to unwrap nullable values safely?

!! is used to force unwrap the nullable type to get the value. If the value returned is a null, it would lead to a runtime crash. Hence a !! operator should be only used when you’re absolutely sure that the value won’t be null at all. Otherwise, you’ll get the dreaded null pointer exception. On the other hand, a ?. is an Elvis Operator that does a safe call.
We can use the lambda expression let on the nullable value to unwrap safely as shown below.
kotlin interview questions let
Here the let expression does a safe call to unwrap the nullable type.

Explain the Differences Between ? and !! in Terms of Null Safety


Kotlin provides two different mechanisms for unwrapping the contents of a nullable type. The Elvis operator ‘?’ provides a safe call and doesn’t crash your program if the content is of type null. However, on the other hand, !! is used for force unwrapping the contents of a nullable variable. This is performed during runtime and thus may lead to a potential system crash if the value returned is null. So, you should only use the !! modifier when you’re certain about the value of your variables.

What is The Billion Dollar Mistake? What is The Billion Dollar Mistake?

Expert
Answer

Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake.

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. In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that can not (non-null references).

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object-oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

Tony Hoare at QCon London in 2009 https://en.wikipedia.org/wiki/Tony_Hoare

How to ensure null safety in Kotlin?

One of the major advantages of using Kotlin is null safety. In Java, if you access some null variable then you will get a NullPointerException. So, the following code in Kotlin will produce a compile-time error:

var name: String = "Android"
name = null //error

So, to assign null values to a variable, you need to declare the name variable as a nullable string and then during the access of this variable, you need to use a safe call operator i.e. ?.

var name: String? = "Android"
print(name?.length) // ok
name = null // ok

What is the difference between safe calls(?.) and null check(!!)?

Safe call operator i.e. ?. is used to check if the value of the variable is null or not. If it is null then null will be returned otherwise it will return the desired value.

var name: String? = "MindOrks"
println(name?.length) // 8
name = null
println(name?.length) // null

If you want to throw NullPointerException when the value of the variable is null, then you can use the null check or !! operator.

var name: String? = "MindOrks"
println(name?.length) // 8
name = null
println(name!!.length) // KotlinNullPointerException

Learn more about safe calls(?.) and null check(!!) from MindOrks blog.

Explain the concept of null safety in Kotlin.

Kotlin's type system aims to eradicate null references from the code. If a program throws NullPointerExceptions at runtime it might result in application failure or system crashes. If the Kotlin compiler finds a null reference it throws a NullPointerException.

The Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). Null cannot be stored in a String variable. We get a compiler error if we try to assign null to the variable. 

var a: String = "interview"
a = null // results in compilation error

If we want the above string to be able to hold null value as well, we can declare it of type nullable using the ‘?’ operator after the String keyword as follows :

var a: String? = "interview"
a = null // no compilation error

Kotlin provides Safe Call (?.), Elvis (?:) and Not Null Assertion (!!) operators which define what needs to be done in case of a null encounter. This makes the code more reliable and less prone to errors. Thus, Kotlin enforces null safety by having nullable, non-nullable type variables and the different operators to tackle null encounters.

5. Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin.

Safe Call operator ( ?. ) -  Null comparisons are trivial, but the number of nested if-else expressions can be exhausting. So, in Kotlin, there's a Safe call operator,?, that simplifies things by only doing an action when a specified reference holds a non-null value. It allows us to use a single expression to perform both a null check and a method call.

For example,

The following expression in Kotlin

name?.toLowerCase() 

is equivalent to the following

if(name != null) 
   name.toLowerCase()
else
   null 

Elvis Operator ( ?: ) - When the original variable is null, the Elvis operator is used to return a non-null value or a default value. In other words, the elvis operator returns the left expression if it is not null, otherwise, it yields the right expression. Only if the left-hand side expression is null is the right-hand side evaluated. 

For example,

The following expression in Kotlin

val sample1 = sample2 ?: "Undefined"

is equivalent to the following

val sample1 = if(sample2 != null) 
       sample2
     else 
       "Undefined"

Furthermore, on the right side of the Elvis operator, we may use throw and return expressions, which is particularly handy in functions. As a result, instead of returning a default value on the right side of the Elvis operator, we can throw an exception. For example,

val sample1 = sample2 ?: throw IllegalArgumentException("Invalid")

Not Null Assertion Operator ( !! ) - If the value is null, the not null assertion (!!) operator changes it to a non-null type and throws an exception.

Anyone who wants a NullPointerException can ask for it explicitly with this operator.

For example,

// KOTLIN
fun main(args: Array<String>) {
   var sample : String?  = null
   str!!.length
}

The above code snippet gives the following output:-

Exception in thread "main" kotlin.KotlinNullPointerException


Smart Cast

What is Smart Casting in Kotlin?


Smart cast is a simple but useful mechanism that allows programmers to reduce most null-based errors. The Kotlin compiler does this by inferring the variables. We’ve witnessed it in a previous question. Below, we’re illustrating a simple example of smart casting in Kotlin.

fun test(a: Any) {
        if (a is String) {
            print(a.length)    // a is cast to String by the compiler automatically
        }
}

Aaaaa

Unsafe and Safe Cast

What is Smart Casting in Kotlin?


Smart cast is a simple but useful mechanism that allows programmers to reduce most null-based errors. The Kotlin compiler does this by inferring the variables. We’ve witnessed it in a previous question. Below, we’re illustrating a simple example of smart casting in Kotlin.

fun test(a: Any) {
        if (a is String) {
            print(a.length)    // a is cast to String by the compiler automatically
        }
}


aaaaa


Elvis Operator

How can you handle null exceptions in Kotlin?

Elvis Operator is used for handling null expectations in Kotlin.

What is Null Safety in Kotlin?

Kotlin it handles Null Pointer Exceptions and used to eliminate the risk of occurrence of NullPointerException in real-time.

The ways to handle Null Safety –

1. Checks for null in conditions
2. Use Safe Call Operator (?.)
3. Use Elvis Operator (?:)

Example

  1. fun main(args: Array){
  2. // variable is declared as non-null by default
  3. var str: String = "Hi, Anil!"
  4. // kotlin prevents you assign a null to a non-nullable variable
  5. // str=null //assing null to a causes complilation error
  6. println("str is : $str")
  7. // variable is declared as nullable
  8. var str1: String? = "Hi, Anil!"
  9. println("str1 is : $str1")
  10. str1 = null
  11. println("str1 is : $str1")
  12. }
How to handle a null operator?
 
We can handle all the nullable values using the Elvis operator.

Do we have a ternary operator in Kotlin just like java?

No, we don't have a ternary operator in Kotlin but you can use the functionality of ternary operator by using if-else or Elvis operator.

What is Elvis operator in Kotlin?

In Kotlin, you can assign null values to a variable by using the null safety property. To check if a value is having null value then you can use if-else or can use the Elvis operator i.e. ?: For example:

var name:String? = "Mindorks"
val nameLength = name?.length ?: -1
println(nameLength)

The Elvis operator(?:) used above will return the length of name if the value is not null otherwise if the value is null, then it will return -1.

When would you use Elvis operator in Kotlin? When would you use Elvis operator in Kotlin?

Mid
Answer

The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#. The Elvis operator is the ternary operator with its second operand omitted.

x ?: y // yields `x` if `x` is not null, `y` otherwise.

If x isn't null, then it will be returned. If it is null, then the y will be returned.



Aaaaas

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

CustomView based Android interview questions and answers