Kotlin - Data class

What are data classes?
A data class is a class that only contains state and does not perform any operation.

The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.

In particular, it gives us all this for free:

The properties declared in the constructor: this technically is not exclusive to a data class, but it avoids all the boilerplate of getters and setters, in addition to the constructor.
equals() / hashCode()

A set of functions called componentX(), which allow us to do a cool thing we’ll see later.
A copy()method, very useful when we use immutable objects


in java if we want to create simple class should be like this


			    
	public class Employee {
    private String empName;
    
    private String id;
    public String getempName() {
        return empName;
    }
    public void setempName(String empName) {
        this.empName = empName;
    }
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee Employee = (Employee) o;
        if (empName != null ? !empName.equals(Employee.empName) : Employee.empName != null) return false;
       
        return id != null ? id.equals(Employee.id) : Employee.id == null;
    }
    @Override public int hashCode() {
        int result = empName != null ? empName.hashCode() : 0;
       
        result = 31 * result + (id != null ? id.hashCode() : 0);
        return result;
    }
    @Override public String toString() {
        return "Employee{" +
                "empName='" + empName + ''' +
              
                ", id='" + id + ''' +
                '}';
    }
}

 

Now this code can be written in kotlin as

 


			

data class Person(var empName: String,  var id: String)

 

Creating an Instance of a Data Class

Data classes are instantiated in the same manner as a standard class:


val employee: Employee = Employee("Epic Garge", 8)
	

We can now access the members of game:


print(employee.empName) // "Epic Garge"
print(employee.id) // 8
employee.id = 10
    	

Visibility Modifiers

We can control the visibility modifiers of the getters/setters generated by providing them in the constructor:


data class Emplyee(private val empName: String,  private var id: Int)
    	

Read-Only Fields

If we only wish to expose getters and not setters, we just provide val instead of var for each field (val properties are Kotlin’s equivalent of final in Java). In the below example, name and reviewScore have read/write access, while publisher is read-only


data class Emplyee(private val empName: String,  private var id: Int)
    	

Subscribe For Daily Updates