Reputation: 3236
Coming from a Swift world I'm trying to figure out how to use comparable functions like min()
or max()
on an array of objects. In Swift I would use the comparable protocol -
class Car: Comparable {
let year: Int
static func < (lhs: Car, rhs: Car) -> Bool {
return lhs.year < rhs.year
}
static func == (lhs: Car, rhs: Car) -> Bool {
return lhs.year == rhs.year
}
}
But how would you do the same in Kotlin? I've tried this but I'm not sure if it's the right approach, or how I would implement the iterable function -
data class Car(val year: Int): Comparable<Car>, Iterable<Car> {
override fun compareTo(other: Car) = when {
this.year < other.year -> -1
this.year > other.year -> 1
else -> 0
}
override fun iterator(): Iterator<Car> {
TODO("not implemented")
}
}
Upvotes: 0
Views: 628
Reputation: 39853
Regarding your implementation there's no issue, but you could make it simpler:
data class Car(val year: Int): Comparable<Car> {
override fun compareTo(other: Car) = year - other.year
}
You should not implement the Iterable
interface, because this would make the Car
a kind of a collection.
Running the following example with the given Car
implementation
listOf(Car(2004), Car(2007), Car(2001)).run {
println(this)
println(min())
println(max())
println(sorted())
}
yields the output of
[Car(year=2004), Car(year=2007), Car(year=2001)]
Car(year=2001)
Car(year=2007)
[Car(year=2001), Car(year=2004), Car(year=2007)]
Upvotes: 1