2

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?

Tim
  • 41,901
  • 18
  • 127
  • 145
Zorgan
  • 8,227
  • 23
  • 106
  • 207

2 Answers2

8

.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"

elixenide
  • 44,308
  • 16
  • 74
  • 100
Abdul Kawee
  • 2,687
  • 1
  • 14
  • 26
1

Normal toString() from kotlin.Any should throw exception if value is null. But, there is also method Any?.toString() from kotlin.kotlin_builtins.

As kotlin.Any.toString cannot be applied to nullable type your compiler knows what method should use.

See this example:

fun test() {
    val possibleNull: Any? = Any()
    val notNull: Any = Any()

    possibleNull.toString()

    possibleNull?.toString()
    possibleNull!!.toString()
    notNull.toString()
}

If you write this in IntelliJ you'll see that the first toString() is actually extenstion method, because that one can be applied to that type. All others examples will call "normal" toString() which would work as you told.

enter image description here

Cililing
  • 4,303
  • 1
  • 17
  • 35