Don't allow coercing null to string with platform calls

Here’s the actual example I came across:

// prefs: android.content.SharedPreferences
val cachedContents = prefs.getString("key", null) ?: return null // never returns null
return foo(cachedContents)
  • null is coerced to the string “null” via the toString() extension
  • The returned type is a String!, which is inferred to be String? because of the use of the elvis operator

This is all technically functioning as intended, but it leads to very misleading code. I don’t think it’s reasonable to change the platform type to anything but String!, but it might be reasonable to forbid passing null as a string to a platform call or, at the least, generate a compiler warning.

Kotlin does not apply any implicit coercions, so the toString() extension is irrelevant here; converting the string to “null” is probably what the getString() method does internally. Therefore, I don’t see why the String type should be treated any differently from any other type when it’s passed to a parameter of a platform type.

ack, you’re right, it’s Android, not kotlin. Sorry, I should have spent more time researching before posting.