Mahabub Mahabub - 4 months ago 5x
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){ = id; = name;
// getter/ setter

then I can create new Object and get json as following

A a= new A()

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

which gives me result


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
; which i don't want

So how to do this???


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,