Slackbot
03/17/2023, 4:46 PMSam
03/17/2023, 4:47 PM@UnsafeVariance annotation — for example the built-in collections do thisSam
03/17/2023, 4:48 PMYoussef Shoaib [MOD]
03/17/2023, 4:52 PMsealed class Bounds<in T : Comparable<T>> {
abstract operator fun contains(value: T): Boolean
}
object Unbounded : Bounds<Comparable<Comparable<*>>>() {
override fun contains(value: Comparable<Comparable<*>>) = true
}Youssef Shoaib [MOD]
03/17/2023, 4:52 PMSam
03/17/2023, 4:53 PMclass Unbounded<in T : Comparable<T>> : Bounds<T>() {
override fun contains(value: T) = true
}
if you can live with it not being a singletonYoussef Shoaib [MOD]
03/17/2023, 4:54 PMComparable<*> would be a subtype of Comparable<T> where T: Comparable<T> but I guess not?Youssef Shoaib [MOD]
03/17/2023, 4:56 PMsealed class Bounds<in T : Comparable<T>> {
abstract operator fun contains(value: T): Boolean
}
object Unbounded : Bounds<Comparable<Any?>>() {
override fun contains(value: Comparable<Any?>) = true
}
Which I think (maybe?) makes more sense. Comparable's T is in, and so Comparable<*> is in reality Comparable<Nothing>, which I think then isn't a subtype of Comparable<Comparable<Nothing>> because it can only accept arguments of type Nothing.
Hopefully that makes a bit more sense lol! Generic variance is truly out of this world...Youssef Shoaib [MOD]
03/17/2023, 5:44 PMsealed class Bounds<in T : Comparable<T>> {
abstract operator fun contains(value: T): Boolean
}
object Unbounded : Bounds<Comparable<Any?>>() {
override fun contains(value: Comparable<Any?>) = true
}
fun <T: Comparable<T>> unbounded(): Bounds<T> = Unbounded as Bounds<T>
interface B : Comparable<B>
class A(val spec: Bounds<B> = unbounded())Michael de Kaste
03/27/2023, 11:28 AMsealed interface Range<T : Comparable<T>>{
interface Open<T : Comparable<T>> : Range<T> {
override fun contains(value: T) = true
}
}
internal object OpenRange = Range.Open<Nothing>
fun <T : Comparable<T>> openRange() = Range.OPEN as Open<T>
its akin to how List<T> and emptyList() is used by kotlin self, you only have a cast problem, but you'll have to surpress that. Kotlin itself uses unsafevariance and stuff to surpress the cast warnings. The main takeaway is that unbounded should probably be Nothing, not Any?