https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

elect

02/27/2023, 6:19 PM
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

Laertes Moustakas

02/27/2023, 6:31 PM
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

Youssef Shoaib [MOD]

02/27/2023, 7:20 PM
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

elect

02/27/2023, 7:54 PM
I don't think so, but let me check
y

Youssef Shoaib [MOD]

02/27/2023, 7:56 PM
What does your
Value
class look like btw?
e

elect

02/27/2023, 7:59 PM
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

Youssef Shoaib [MOD]

02/27/2023, 8:17 PM
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
8 Views