I'm using retrofit and kotlin for my andorid app.
For one of my APIs, I have the following data classes
class Set(val set_id: Long, val tickets: List<Ticket>, val timer: Int) {}
class Ticket(val ticket_id: Long, val rows: List<Row>) {}
class Row(val row_id: Long, val row_numbers: List<Int>) {}
Sample JSON DATA
{
"set_id": 60942,
"tickets": [
{
"ticket_id": 304706,
"rows": [
{
"row_id": 914116,
"row_numbers": [
0,
11,
21,
0,
42,
52,
0,
76,
85
]
}
]
}
],
"timer": 12
}
Set
class contains a list of Ticket
and each ticket has a list of Row
My JSON object contains only these values and it is working fine till here. Retrofit mapping is also working.
Problem:
I want to add my own a boolean field/variable isPlaying
for class Ticket
, which will be updated in the app later. But, this field should be set to true by default.
So I've tried this
class Ticket(val ticket_id: Long, val rows: List<Row>, var isPlaying: Boolean = true) {}
and this
class Ticket(val ticket_id: Long, val rows: List<Row>) {
var isPlaying: Boolean = true
}
NOTE: JSON doesn't have isPlaying
key, I want it for app logic only.
Both did not work, isPlaying
is always showing false
. I want it to be true
by default.
Please, help me out. Thank you!
In object-oriented programming (OOP), a class contains both properties and functions. However, classes that serve only as data models focus on properties. In such classes, the compiler can derive some functionality from its member properties.
Override function in Kotlin We have one Data class "myClass" and we have one data member "myValue". We will override the value using the function getValue().
The @SerializedName annotation can be used to serialize a field with a different name instead of an actual field name. We can provide the expected serialized name as an annotation attribute, Gson can make sure to read or write a field with the provided name.
Default arguments would not work in data class in the case when objects are instantiated with retrofit due to parsing library used underneath, which probably creates objects without calling constructor. For example Gson
uses sun.misc.Unsafe
to create objects.
What you can do - is to add backing property for fields that have default values:
class Ticket(
val ticket_id: Long,
val rows: List<Row>,
private var _isPlaying: Boolean? = true
) {
var isPlaying
get() = _isPlaying ?: true
set(value) {
_isPlaying = value
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With