paint-brush
Kotlin: Hacking non Null variable Null!!by@elye.project
1,062 reads
1,062 reads

Kotlin: Hacking non Null variable Null!!

by ElyeJuly 29th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Kotlin: Hacking non Null variable Null!!
Elye HackerNoon profile picture

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.

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