Instruction 2

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Using the Elvis Operator

The Elvis operator (?:) is a convenience operator that enables you to check and assign a value to a variable if it’s not null. This is a cool feature that could save you some lines of code. Without it, your code could look like this:

fun main() {
   val items: Int? = null
   var amount = 0
   if (items != null){
      amount = items
   }
   println("Amount to pay: $amount")
}
Amount to pay: 0
fun main() {
   val items: Int? = null
   val amount = items ?: 0
   println("Amount to pay: $amount")
}
Amount to pay: 0

Using the Null Safe Operator

The null-safe operator is symbolized by ?.. Instead of using the dot notation . to access methods or fields on an object, the null-safe operator makes use of ?. This then ensures that the method call only happens if the object isn’t null. If it is, the method isn’t invoked.

fun main() {
   val apple: Int? = null
   val orange: Int = 5

   val total = apple?.plus(orange)
   println(total)
}
null
fun main() {
   val apple: Int? = 5
   val orange: Int = 5

   val total = apple?.plus(orange)
   println(total)
}
10

Introducing Let and Run Scope Functions

The let scope function behaves similarly to the null-safe ?. operator. In that, it only executes if the object isn’t null. The key difference here is that if it’s not null, it makes the object available in the let function for further use. The former doesn’t offer this capability. Make the following modifications to the previous example to use let:

fun main() {
   val apple: Int? = 5
   val orange: Int = 5

   val total = apple?.let { orange.plus(it) }
   println(total)
}

Understanding the NotNull Delegate

A delegate is a software design pattern where an object delegates its duties to another object. The notNull delegate allows a variable to be declared as non-nullable but not during initialization. It must be a mutable variable since you’ll have to provide its value later on in the program.

import kotlin.properties.Delegates

var items by Delegates.notNull<Int>()

fun main() {
   items = 5
   println(5)
}

Working with the Lateinit Modifier

This modifier is added to a variable that will be initialized later on in the program, as opposed to at the time of declaration. It behaves similarly to Delegate.notNull() above.

lateinit var book: Book

fun main() {
   book = Book()
   book.display()
}

class Book {
   fun display(){
       println("lateinit modifier works similar to Delegate.notNull()")
   }
}
lateinit modifier works similarly to Delegate.notNull()
See forum comments
Download course materials from Github
Previous: Instruction 1 Next: Instruction 3