Contenido del Curso
Android Development with Kotlin
Android Development with Kotlin
Challenge: 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’s980
units per year of experience.
Use the null safety operations we covered in the last chapter to solve this problem!
Main
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.
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") }
¡Gracias por tus comentarios!