Gasan
09/19/2022, 8:06 PMCasey Brooks
09/19/2022, 8:12 PMGasan
09/19/2022, 8:19 PMCasey Brooks
09/19/2022, 8:39 PMinterface ObjectValidator<T> {
fun isValid(instance: T): Boolean
}
data class Person(val name: String) {
class Validator : ObjectValidator<Person> {
override fun isValid(instance: Person) = return instance.name.isNotBlank()
}
}
fun main() {
val person = Person("John Doe")
val personValidator = Person.Validator()
val isValid = personValidator.isValid(person)
}
Compare this to using the companion object to implement ObjectValidator
, which is much more confusing to read when it’s used
fun main() {
val person = Person("John Doe")
val personValidator = Person
val isValid = personValidator.isValid(person)
}
Casey Brooks
09/19/2022, 8:41 PMObjectValidator
, it doesn’t automatically associate itself to the Person
class. There’s no real relation between a companion object and the class it’s with, other than syntax (and reflection). A class kinda knows about its companion object, but a companion object doesn’t really know anything about the class it’s a companion to
data class Person(val name: String) {
companion object : ObjectValidator<Person> { // still needs the <Person> type parameter
override fun isValid(instance: Person) = instance.name.isNotBlank()
}
}
Gasan
09/19/2022, 8:49 PMCasey Brooks
09/19/2022, 8:52 PMinner class
in Kotlin for it to work like a normal (non-static) Java inner classGasan
09/19/2022, 8:53 PMCasey Brooks
09/19/2022, 8:57 PMGasan
09/19/2022, 8:59 PMCasey Brooks
09/19/2022, 9:06 PMGasan
09/19/2022, 9:11 PMCasey Brooks
09/19/2022, 9:23 PMGasan
09/19/2022, 9:29 PMCasey Brooks
09/19/2022, 10:04 PMTobias Berger
09/20/2022, 9:31 AMGasan
09/21/2022, 11:59 AMGasan
09/21/2022, 11:59 AM