Mahabub Mahabub - 7 months ago 29
JSON Question

How to handle an empty param in Kotlin?

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 a new Object and get json as following

A a= new A()

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

which gives me the 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,