making use of a basic unit test:
class ExampleUnitTest {
@Test
fun fooTest() {
var gson = Gson()
data class Foobar( val foo: String )
val foobar = gson.fromJson("""{"foo":"bar"}""",Foobar::class.java)
val jsonString = gson.toJson(Foobar("bar"))
assertEquals(null, foobar)
assertEquals(null, jsonString)
}
}
this test fails:
Expected :null<null>
Actual :java.lang.String<null>
moving the class outside of the method :
data class Foobar( val foo: String )
@Test
fun fooTest() {
var gson = Gson()
val foobar = gson.fromJson("""{"foo":"bar"}""",Foobar::class.java)
val jsonString = gson.toJson(Foobar("bar"))
assertEquals(null, foobar)
assertEquals(null, jsonString)
}
Expected :null
Actual :Foobar(foo=bar)
as well as
Expected :null
Actual :{"foo":"bar"}
this is a good thing, this means that we were expecting it to be null, but instead the test failed because our variables actually had values. Your issue is caused by having the data class inside the method, in your case this method is onCreate, moving it out resolves the issue