alex cole
01/27/2021, 11:23 PMT: Number
and another value in the class is initialized as 0 but that type of Number. How do I do that?
class Complex<T: Number> {
var real: T
var imaginary: T
constructor (real: T) {
this.real = real
imaginary = 0.ofType(T) // this is where help is needed
}
constructor (real: T, imaginary: T) {
this.real = real
this.imaginary = imaginary
}
}
Endre Deak
01/27/2021, 11:35 PMconstructor(real: T, imaginary: T)
and call it with the corresponding zero value.Albert Chang
01/28/2021, 7:58 AMclass Complex<T : Number>(var real: T, var imaginary: T)
@Suppress("FunctionName", "UNCHECKED_CAST")
fun <T : Number> Complex(real: T): Complex<T> =
when (real) {
is Int -> Complex(real, 0 as T)
is Long -> Complex(real, 0L as T)
is Float -> Complex(real, 0f as T)
is Double -> Complex(real, 0.0 as T)
// Other types
else -> throw IllegalArgumentException()
}
Glen
01/28/2021, 11:25 AMconstructor (real: T) { this.real = real imaginary = 0 as T }
alex cole
01/28/2021, 2:39 PMwarning: unchecked cast: Int to T
Endre Deak
01/28/2021, 6:08 PMNumber
does not give you that kind of abstraction that you are looking for. In your case, ideally Number
would provide an abstract method for ZERO
, but in Kotlin, it only provides you a set of conversion methods. With that in mind, you still have a few options to consider:
a. tying your structure to a concrete number implementation (e.g. Double
)
b. implementing your own Number
abstraction and wrap all the number types to that (I don’t recommend this one)
c. keep going with the existing Number
class and deal with the unchecked cast warning.Glen
01/28/2021, 10:16 PMalex cole
01/29/2021, 1:28 AMAlbert Chang
01/29/2021, 1:47 AMNumber.ZERO
abstract val it returns Number
instead of the specific child type (T : Number
) so you have to use unchecked cast anyway.alex cole
01/30/2021, 5:14 PMGlen
01/31/2021, 10:41 AMalex cole
01/31/2021, 7:20 PM> kotlinc -d main.jar main.kt
main.kt:15:19: warning: unchecked cast: Int to T
imaginary = 0 as T
^
> kotlin -classpath main.jar MainKt
Success
0.0 + 0i
>
Glen
02/01/2021, 3:08 AMDave K
02/04/2021, 5:09 AMthis.imaginary = real::class.cast(0)
Dave K
02/04/2021, 5:14 AMclass Complex<T : Number>(var real: T, var imaginary: T = real::class.cast(0))
providing the default second argument allows the caller to provide either just real or both argumentsDave K
02/04/2021, 5:17 AMAlbert Chang
02/04/2021, 5:26 AMkotlin.reflect.KClasses.cast
does not support conversion between numeral types. Try running println(0f::class.cast(0))
and you'll get a ClassCastException
.Dave K
02/04/2021, 5:30 AMDave K
02/04/2021, 3:17 PM