If you are a Java programmer you may be tired of having troublesome implementation of setter, getter, hashcode, toString once.
Does not the IDE implement it automatically, or use a tool like lombok not to think deeply about this problem?
In Kotlin, there is a mechanism to automatically generate these troublesome declarations by attaching the qualifier "data" at the position of Class declaration
This is sample of Data Class (Person class).
data class Person (val name: String, val age: Int)
This is how to use person class.
var bob = Person ("Bob", 33)
var bob 2 = Person ("Bob", 33)
println (bob === bob2) // false
println (bob == bob2) // true
println (bob.equals (bob2)) // true
println (bob.hashCode ()) // 2075948
println (bob.toString ()) // Person (name = Bob, age = 33)
Decompile with JAD
Decompile the person class and convert the automatically implemented code to Java
$ jad Person.class
Parsing Person.class ... Generating Person.jad
Could not fully decompile method hashCode
The method of hashcode could not be decompiled.
I'll check hashcode()
at next post.
Decompiling result of java: Person class
import kotlin.jvm.internal.Intrinsics;
public final class Person
{
public final String getName ()
{
return name;
}
public final int getAge ()
{
return age;
}
public Person (String name, int age)
{
Intrinsics.checkParameterIsNotNull (name, "name");
super ();
this.name = name;
this.age = age;
}
public final String component 1 ()
{
return name;
}
public final int component 2 ()
{
return age;
}
public final Person copy (String name, int age)
{
Intrinsics.checkParameterIsNotNull (name, "name");
return new Person (name, age);
}
public static volatile Person copy $ default (Person person, String s, int i, int j, Object obj)
{
if ((j & 1)! = 0)
s = person.name;
if ((j & 2)! = 0)
i = person.age;
return person.copy (s, i);
}
public String toString ()
{
append ("age ="). append (age). append (")"). toString (); return (new StringBuilder ()). append ("Person (name =
}
public int hashCode ()
{
name;
if (name == null) goto _ L 2; else goto _ L 1
_L1:
hashCode ();
goto _ L 3
_L2:
JVM INSTR pop;
false;
_L3:
31;
JVM INSTR imul;
age;
JVM INSTR iadd;
return;
}
public boolean equals (Object obj)
{
label0:
{
if (this! = obj)
{
if (! (obj instance of Person))
break label 0;
Person person = (Person) obj;
if (! Intrinsics.areEqual (name, person.name) || (age! = person.age))
break label 0;
}
return true;
}
return false;
}
private final String name;
private final int age;
}
Now, we checked automatic generation of hashCode, equals, toString, copy, # copy methods.
Next time,I check hashcode's bytecode.
thank you for your reading.