Klitos Kyriacou
05/21/2025, 3:10 PMKlitos Kyriacou
05/21/2025, 3:15 PMfun <T: Comparable<T>> getComparables() : Pair<T, T>
= when (Random.nextBoolean()) {
true -> Pair(1, 2)
false -> Pair("a", "b")
}
Also won't compile:
fun <T> getComparables() : Pair<Comparable<T>, Comparable<T>>
= when (Random.nextBoolean()) {
true -> Pair(1, 2)
false -> Pair("a", "b")
}
This compiles but doesn't guarantee that the types are the same:
fun getComparables() : Pair<Comparable<*>, Comparable<*>>
= when (Random.nextBoolean()) {
true -> Pair(1, 2)
false -> Pair("a", "b")
}
Michael Krussel
05/21/2025, 3:30 PMgetComparable<Instant>()
and it would return either a pair of string or a pair of ints, which does not implement Pair<Instant>
.
The only valid return type for this is Pair<Any>
or Pair<Comparable<Any>>
ephemient
05/21/2025, 3:36 PMPair<Any, Any>
is possibleephemient
05/21/2025, 3:37 PMInt
nor String
is Comparable<Any>
, because Comparable<in T>
is contravariantephemient
05/21/2025, 3:40 PMdata class ComparablePair<T : Comparable<T>>(val first: T, val second: T)
then you could define
fun getComparables(): ComparablePair<*>
but that's not all that much more usefulMichael Krussel
05/21/2025, 3:47 PMMichael Krussel
05/21/2025, 3:47 PMPair<String, String> | Pair<Int, Int>
ephemient
05/21/2025, 3:49 PMPair<*, *>
due to erasure, and you can do a tagged union now with sealed
Youssef Shoaib [MOD]
05/21/2025, 4:53 PMComparablePair
is the solution here, to be consumed like:
getComparables().doSomething()
fun <T: Comparable<T>> ComparablePair<T>.doSomething() = first < second // for example
Klitos Kyriacou
05/21/2025, 5:10 PM