Learning Kotlin: Data Classes

Submitted by Robert MacLean on Thu, 06/21/2018 - 09:00

More Information

WOW! Data Classes are awesome! I really like a lot of how classes are handled in Kotlin, but Data Classes are the pinnacle of that work. The effort for this Koan is to convert this Java class to Kotlin:

  1. package i_introduction._6_Data_Classes;
  2.  
  3. import util.JavaCode;
  4.  
  5. public class JavaCode6 extends JavaCode {
  6.  
  7.     public static class Person {
  8.         private final String name;
  9.         private final int age;
  10.  
  11.         public Person(String name, int age) {
  12.             this.name = name;
  13.             this.age = age;
  14.         }
  15.  
  16.         public String getName() {
  17.             return name;
  18.         }
  19.  
  20.         public int getAge() {
  21.             return age;
  22.         }
  23.     }
  24. }

and what does that look like in Kotlin?

  1. data class Person(val name: String, val age: Int)

Yup, a single line. The data annotation adds a number of important functions (like ToString and copy). We then declare the class with a constructor which takes two parameters which both become properties.

Another important aspect I learnt with this one is that Kotlin has both a val and var keyword for variables. We have seen var already and val is for read-only variables.