gson - Kotlin not nullable value can be null? -
i have backend return me json.
i parse class:
class somedata( @serializedname("user_name") val name: string, @serializedname("user_city") val city: string, var notnullablevalue: string) use gson converter factory:
retrofit retrofit = new retrofit.builder() .baseurl(endpoint) .client(okhttpclient) .addconverterfactory(gsonconverterfactory.create(gson)) .addcalladapterfactory(rxjava2calladapterfactory.create()) .build(); and in interface:
interface myapi { @get("get_data") observable<list<somedata>> getsomedata(); } then retrieve data server (with rxjava) without error. expected error because thought should (to prevent gson converter error, because notnullablevalue not present in json response):
class somedata @jvmoverloads constructor( @serializedname("user_name") val name: string, @serializedname("user_city") val city: string, var notnullablevalue: string = "") after data received backend , parsed somedata class constructor without def value, value of notnullablevalue == null.
as understand not nullable value can null in kotlin?
yes, because you're giving default value. ofcourse never null. that's whole point of default value.
remove ="" constructor , error.
edit: found issue. gson uses magic sun.misc.unsafe class has allocateinstance method considered unsafe because skip initialization (constructors/field initializers , like) , security checks. there answer why kotlin non-nullable field can null. offending code in com/google/gson/internal/constructorconstructor.java:223
some interesting details unsafe class: http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
Comments
Post a Comment