Reputation: 21
I got strange results with null and strings:
"" + null result is null,
null + "" result is null
"bbb" + null result is "bbbnull"
I expected "", "" and "bbb"
Where did I go wrong?
Upvotes: 0
Views: 80
Reputation: 2421
When you attach a string as null + ""
, it means that the compiler will interpret it null.toString()
and ""
.
And for null.toString()
, check out Kotlin's toString()
extension.
fun Any?.toString(): String {
if (this == null) return "null"
// after the null check, 'this' is autocast to a non-null type, so the toString() below
// resolves to the member function of the Any class
return toString()
}
As you can see, when you pass in null, it will print "null". That's why you get "null" instead of not seeing it.
Upvotes: 2