Why my data class giving null values unless i applied default on it?

Viewed 1866

I am trying to show data from the server using data class of kotlin. It's almost working fine but some case whenever I fetch a response I don't know why it is still giving null values unless I add a default value ("") for msg.

  1. This is my data class

    data class ViewcardModel(
            val msg: String = "",  // here is default values
            val cartcnt: String = "",
            val order_total: Int = 0,
            val status: Boolean = false          
    )
    
  2. This is my response from server

    {
      status = false  // server response
    }
    
2 Answers

You're probably using something like GSON to instantiate the instances of your model. These tools use reflection to create instances, and therefore the default parameter value of your primary constructor will never take effect (since it's never called).

What you need is the same as what this question is about:

Setting Default value to a variable when deserializing using gson

A custom deserializer is probably what you'll end up with.

You should pass the value into data class like this

  val s= ViewcardModel(status=false)
  println(s.toString())
  val s1= ViewcardModel(msg="hello",status=false)
  println(s1.toString())

output

ViewcardModel(msg=, cartcnt=, order_total=0, status=false)
ViewcardModel(msg=hello, cartcnt=, order_total=0, status=false)
Related