Classes & Objects
A class's constructor parameters can be declared right in the class header, dramatically shortening what would be several lines in Java.
Example: a data class
data class Student(val name: String, val track: String)
fun main() {
val ada = Student("Ada", "Frontend")
println("${ada.name} is studying ${ada.track}")
}
Ada is studying Frontend
Compare this one line to Java's Student class from the Java tutorial —
Kotlin's data class automatically generates useful
boilerplate a Java class needs written by hand: a readable
toString(), equality checks comparing actual field values
instead of just object identity, and more. This is exactly what makes it
the right choice for classes that are mainly just holding data — which is
precisely what most Android UI models look like in practice.
data class Student(val name: String, val track: String)
fun main() {
val ada = Student("Ada", "Frontend")
println("${ada.name} is studying ${ada.track}")
}
Ada is studying Frontend