Ruckus
03/17/2023, 4:46 PMsealed class Bounds<in T : Comparable<T>> {
abstract operator fun contains(value: T): Boolean
}
And I want
object Unbounded : Bounds<Any?> {
override fun contains(value: Any?) = true
}
However, I cannot as Any?
violates the type bound. Is there a way to specify the type to make this work?Sam
03/17/2023, 4:47 PM@UnsafeVariance
annotation — for example the built-in collections do thisRuckus
03/17/2023, 4:48 PMin
and out
. My goal is to specify that Unbounded
works for any comparable.Sam
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
}
Sam
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?sealed 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...Ruckus
03/17/2023, 5:29 PMinterface B : Comparable<B>
class A(val spec: Bounds<B> = Unbounded) // Error is now here
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())
Ruckus
03/17/2023, 6:29 PMMichael 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?