DEV Community

Cover image for πŸš€ Kotlin's Key Features #1
Saleemuddin Khan
Saleemuddin Khan

Posted on • Edited on

πŸš€ Kotlin's Key Features #1

🏹 Null Safety in Kotlin
Dodging the Null Pointer Exception, the Kotlin wayπŸ€“πŸ€“

➀ Concept of Strict Null Safety in Kotlin
β€’ Safe Call Operator ( ?. ) in Kotlin
β€’ Elvis Operator ( ?: ) in Kotlin
β€’ Not Null Assertion ( !! ) in Kotlin.

Strict Null Safety

  • Kotlin allows to store β€œNull” values in a variable.
  • In Kotlin, the variables can be made of Null types by just adding a β€œ?” symbol to the right side of the data type.
  • A nullable type variable means it can also hold β€œNull” as a value in it.
  • A non-nullable type variable means that it can not hold β€œNull” as a value in it.

Safe Call Operator

  • The safe call operator is simply a question mark followed by a dot ( ?. )
  • The safe call operator in Kotlin, is one of the methods to impose β€œNull Safety Checks” on the nullable variables.
  • If the left-hand side of the operator is null, then it will return null value.
  • If the left-hand side of the operator is not null, then it will return the result of the right-hand side expression.

Elvis Operator

  • The elvis operator is represented by a question mark followed by a colon ( ?: )
  • The elvis operator in Kotlin, is one of the methods to impose β€œNull Safety Checks” on the nullable variables.
  • If the first operand is not null, then this operand will be returned by the elvis operator.
  • If the first operand is null, then second operand will be returned by the elvis operator.

Not Null Assertion

  • The Not Null Assertion is represented by a double exclamation mark (!!)
  • The Not Null Assertion in Kotlin, is another tool to deal with nullity.
  • This operator explicitly casts nullable variables to non-nullable variables.

Top comments (0)