Learning Kotlin: Data Classes

Submitted by Robert MacLean on Thu, 06/21/2018 - 09:00
**More Information** * [The code being referenced](https://github.com/Kotlin/kotlin-koans/tree/master/src/i_introduction/_6_Data_Classes). * This is the 7th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction) WOW! [Data Classes](https://kotlinlang.org/docs/reference/data-classes.html) are awesome! I really like a lot of how [classes are handled in Kotlin](https://kotlinlang.org/docs/reference/classes.html), but Data Classes are the pinnacle of that work. The effort for this Koan is to convert this Java class to Kotlin: package i_introduction._6_Data_Classes;   import util.JavaCode;   public class JavaCode6 extends JavaCode {       public static class Person {         private final String name;         private final int age;           public Person(String name, int age) {             this.name = name;             this.age = age;         }           public String getName() {             return name;         }           public int getAge() {             return age;         }     } } and what does that look like in Kotlin? 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.