classes
class Target(val host: String, val port: Int) {
fun endpoint() = "$host:$port"
}
The constructor is the primary constructor Properties are declared in the parameter list No boilerplate for simple data carriers
Data classes
data class Host(val ip: String, val port: Int)
data generates equals, hashCode, toString, and copy
Use it for value objects
Do not use it for entities with identity
Inheritance
open class Media(val name: String)
class Song(name: String, val artist: String) : Media(name)
Classes are final by default
open opts into inheritance
That default reduces accidental coupling
Interfaces
interface Scanner {
fun scan(): String
}
Interfaces can hold default implementations Multiple interface implementation is allowed That replaces most uses of multiple inheritance
Sealed hierarchies
sealed class Result {
data class Ok(val value: String) : Result()
data class Err(val message: String) : Result()
}
sealed closes the hierarchy
A when over a sealed type can be exhaustive
The compiler checks the missing case
Next
Collections in 07 collections
Test this in your lab first
Posted