Calling a toString on a nullable type
suggest changeA thing to look out for when using the toString method in Kotlin is the handling of null in combination with the String?.
For example you want to get text from an EditText in Android.
You would have a piece of code like:
// Incorrect:
val text = view.textField?.text.toString() ?: ""
You might expect an empty string when the field does not exist, but this expression is the string "null". toString() is called on the nullable result, and null.toString() is defined to return "null".
// Correct:
val text = view.textField?.text?.toString() ?: ""
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents