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.

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

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.

I hope you appreciate this post and it’s helpful for you. Do share with others.

You could check out my other interesting topics here.

Follow me on medium, Twitter or Facebook for little tips and learning on Android, Kotlin etc related topics. ~Elye~

--

--