is there a way to add locally on the fly additiona...
# getting-started
e
is there a way to add locally on the fly additional boundaries to a type of a local variable? That is, I have
value: Value<N : Number>
and I want temporarily to cast is as
Value<N : Number, N: Comparable<N>
?
l
Think you need to do something like:
Copy code
fun whatever(value: Value<N>): T
    where N: Number,
          N: Comparable<N>
Though I think Number implements Comparable itself. Apparently not, all built-in Number implementations just so happen to implement Comparable too.
y
Would
value as Value<Comparable<N>>
not work? If not, maybe this thread from long ago about intersection types could help? I'm thinking something along the lines of:
Copy code
sealed interface TypeWrapper<out T> {
  companion object: TypeWrapper<Nothing>
}
@Suppress("BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER")
@OptIn(ExperimentalContracts::class)
// R is automatically inferred to just be T1 & T2. 
// the callsite doesn't have to supply a type for R since you can't explicitly write out intersection types.
fun <T1, T2, R> intersection(): TypeWrapper<R>
        where R : T1, R : T2

= TypeWrapper
 
inline fun <reified T> Any.cast(type: TypeWrapper<T>): T = this as T
 
fun main() {
  val value: Any = 5
  println(value.cast(intersection<Number, Comparable<*>, _>()).toDouble())
}
I think you can edit that and perhaps make another function that takes a
TypeWrapper<T>
and outputs a
TypeWrapper<Value<T>>
and use that for the cast. Let me know if that works, and don't hesitate to ask any questions!
e
I don't think so, but let me check
y
What does your
Value
class look like btw?
e
something like this:
Copy code
class SliderRangeVars {
    inner class Value<N> where N : Number, N : Comparable<N> {
        lateinit var cur: N
        lateinit var min: N
        lateinit var max: N
        var resultFlags = 0
    }

    fun <N> values(): Array<Value<*>> = arrayOf(Value<Byte>(), Value<Ubyte>())
}
I also tried experimenting moving
N
on the outer class, but I get other problems later on.. I can add you to the repo, if you want
y
I can't seem to define a
Value<N> where N: Number
without also adding the Comparable boundary. Please do add me to the repo and I'll tinker and see what I can do. My github is @kyay10