Kotlin: Hacking non Null variable Null!!

One of Kotlin most prominent feature above Java is it’s null-safety feature. However, there’s a simple way that make it null, and the code still executable.

Don’t believe? Try the below code.

fun forceNull() {
    val nullBody = """{ "nonNull" : null}"""
    val nullNonNull = Gson().fromJson(nullBody, MyData::class.java)

data class MyData (val nonNullString :String)

It’s also a possible pitfall in actual development environment, as some JSON result could be null, then we’ll get null in our non-null data class variable.

So be careful when you deserialize your JSON. Hopes you watch out this pitfall, and may Kotlin or Gson have a way to deal with this better.

Click “❤” below to share. Thanks! ~Twitter:elye; Facebook:elye

More by Elye

Topics of interest

More Related Stories