steenooo
02/14/2020, 1:16 PMwhen
on a reified generic type?
inline fun <reified F : Foo, reified B : Bar> convert(input: F) : B {
when(B) {
Bar1 -> {}
Bar2 -> {}
}
dfriehs
02/14/2020, 1:20 PMwhen (T::class) {
Boolean::class ->
Float::class ->
Int::class ->
Long::class ->
String::class ->
else ->
}
steenooo
02/14/2020, 1:23 PMMike
02/14/2020, 1:36 PMis
work? That's generally the way to do class comparisons in when
, isn't it?theyann
02/14/2020, 1:36 PMsteenooo
02/14/2020, 1:36 PMtheyann
02/14/2020, 1:37 PMtheyann
02/14/2020, 1:38 PMsteenooo
02/14/2020, 1:38 PMsteenooo
02/14/2020, 1:38 PMsteenooo
02/14/2020, 1:40 PMdfriehs
02/14/2020, 1:42 PM.let { it as T }
chained to the when
, and add a surpression for unchecked casts. It works, but it definitely isn't pretty.steenooo
02/14/2020, 1:45 PMMike
02/14/2020, 1:46 PMsteenooo
02/14/2020, 1:47 PMsteenooo
02/14/2020, 1:50 PMdfriehs
02/14/2020, 2:04 PMoperator fun Number.times(other: Number) = this.widen().let {
when (it) {
is Long -> other.times(it)
is Double -> other.times(it)
else -> throw Exception()
}
}
operator fun Number.times(other: Long) = this.widen().let {
when (it) {
is Long -> other.times(it)
is Double -> other.times(it)
else -> throw Exception()
}
}
operator fun Number.times(other: Double) = this.widen().let {
when (it) {
is Long -> other.times(it)
is Double -> other.times(it)
else -> throw Exception()
}
}
fun Number.widen(): Number = when (this) {
is Byte, is Short, is Int, is Long -> this.toLong()
is Float, is Double -> this.toDouble()
else -> throw Exception()
}
theyann
02/14/2020, 2:07 PM