Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Challenge: Null Safety | Control Flow and Collections
Android Development with Kotlin
course content

Course Content

Android Development with Kotlin

Android Development with Kotlin

1. Kotlin Basics
2. Control Flow and Collections
3. Object-Oriented Programming in Kotlin

bookChallenge: Null Safety

Great to see you here! I could really use your help!

I'm having an issue with Kotlin, specifically with a piece of code where I want to display information about my employee. The problem is that the salary data we received from the form filled out by our accountant is coming through as null. I’m not sure how to handle this yet, but I was told you could help!

Please fix the code below so that it works and displays the correct salary.

Note

Keep in mind that the salary at our company is calculated as follows: For the developer position, it’s 980 units per year of experience.

Use the null safety operations we covered in the last chapter to solve this problem!

kt

Main

copy
12345678910111213
fun main() { val name: String = "John" val position: String = "Developer" var salary: Int = null var yearsOfExperience: Int = 4 val salaryPerYear: Int = 980 for (i in 0 .. yearsOfExperience) { salary = salary + salaryPerYear * i } println("Employee $name has a salary of $salary") }
  • When initializing the variable, use the Elvis operator to assign a salary of 0 if it's null.
  • Use a null check with an if statement or a non-null assertion inside the loop to fix this code.
1234567891011121314151617
fun main() { val name: String = "John" val position: String = "Developer" var salary: Int? = null ?: 0 var yearsOfExperience: Int = 4 val salaryPerYear: Int = 980 for (i in 1 .. yearsOfExperience) { if (salary != null) { salary = salary + salaryPerYear } // or you can use the following solution // salary = salary!! + salaryPerYear } println("Employee $name has a salary of $salary") }
copy

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 8
some-alt