What is the difference between:
definition 1
data class Person (var name:String, var age:Int)
definition 2
class Person (var name:String, var age:Int)
definition 3
class Person (){
var name:String = ""
var age:Int = 1
}
In the 3 cases when i use the autocomplete i saw the same methods availables like a POJO... is the same but 3 differents ways?
Difference in
equals
,hashCode
, &toString
the most important difference between definition 1 and definitions 2 & 3 is that in definition 1, the
equals
,hashcode
andtoString
methods are overridden for you:equals
andhashCode
methods test for structural equalitytoString
method returns a nice, human-friendly stringCode example:
NOTE: in Kotlin, the
==
operator calls an object's.equals()
method. see operator overloading on kotlinlang.org for more info.Difference in constructors
another difference between definitions 1 & 2 and definition 3 is that:
Code example:
The
copy
methodFinally, another difference between definition 1 and definitions 2 & 3 is that in definition 1, a
copy
method is generated for it. Here's an example of how it can be used:Check out the official documentation for data classes on kotlinlang.org!
Definition 1 (
data class Person(var name: String, var age: Int
) is the equivalent ofDefinition 2 (
class Person(var name: String, var age: Int
[nodata
modifier]) is the equivalent ofDefinition 3 is the equivalent of