How to extend a data class with toString

Adding a .toString() extension function would not work because: Extension functions can’t take part in virtual calls (they are resolved statically). In other words, extensions cannot override member functions. If there is a matching member function, it is preferred to the extension. If you add an extension function fun Something.toString() = …, then s.toString() won’t … Read more

Equals method for data class in Kotlin

In Kotlin data classes equality check, arrays, just like other classes, are compared using equals(…), which compares the arrays references, not the content. This behavior is described here: So, whenever you say arr1 == arr2 DataClass(arr1) == DataClass(arr2) … you get the arrays compared through equals(), i.e. referentially. Given that, val arr1 = intArrayOf(1, 2, … Read more

Kotlin Data Class from Json using GSON

Data class: data class Topic( @SerializedName(“id”) val id: Long, @SerializedName(“name”) val name: String, @SerializedName(“image”) val image: String, @SerializedName(“description”) val description: String ) to JSON: val gson = Gson() val json = gson.toJson(topic) from JSON: val json = getJson() val topic = gson.fromJson(json, Topic::class.java)

Extend data class in Kotlin

The truth is: data classes do not play too well with inheritance. We are considering prohibiting or severely restricting inheritance of data classes. For example, it’s known that there’s no way to implement equals() correctly in a hierarchy on non-abstract classes. So, all I can offer: don’t use inheritance with data classes.