Mahabub Mahabub - 6 months ago 8
JSON Question

Kotlin how to handle empty param?

In java we can do following

class A{
int id;
String name;

public A(){}
public A(int id, String name){
this.id = id;
this.name = name;
}
// getter/ setter
}


then I can create new Object and get json as following

A a= new A()
a.setName("test")

System.out.println(new Gson().toJson(a))


which gives me result

{"name":"test"}


In kotlin how can i achive this.
the problem I am facing is kotlin saying primitive type has to be initialized. So in json I am getting both
id
and
name
; which i don't want

So how to do this???

Answer

Kotlint treats null safety seriously thus you have to be explicit about the initialization values. Your example can be translated to:

class A(var id: Int? = null, var name: String? = null)

Notice that the above has both default arguments and a parameterless constructor on the JVM. This let's you write:

val a = A()

As well as:

val a = gson.fromJson(json, A::class.java)
Comments