Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No null safety on variable re-assignment? [duplicate]

Tags:

kotlin

In my android project I have overriden onCheckedChanged() like so:

var numberOfPlayers: Int = 0

override fun onCheckedChanged(group: RadioGroup?, checked: Int) {
    val chosen = activity?.findViewById<RadioButton>(checked)?.text
    numberOfPlayers = chosen.toString().toInt()
}

And I'm confused why numberOfPlayers isn't underlined red as chosen may be null - therefore I'm calling toString() on a possible null value. Why won't this cause a NullPointerException?

like image 294
Zorgan Avatar asked May 13 '26 03:05

Zorgan


1 Answers

.toString() has a safety, meaning if it receives a null value it will return "null" string.

As stated in the official documentation:

fun Any?.toString(): String

Returns a string representation of the object. Can be called with a null receiver, in which case it returns the string "null"

like image 193
Abdul Kawee Avatar answered May 14 '26 16:05

Abdul Kawee