Garret Yoder
01/24/2024, 7:18 PMJoffrey
01/24/2024, 9:23 PMGarret Yoder
01/25/2024, 3:50 PMinline fun <reified T> doSomething(arg1: T) {
when (T::class) {
Boolean::class -> {
}
Int::class -> {
}
}
}
I was wondering if there was a better language convention to do something like above where the compiler could smart-cast arg1 from T into each type since you just checked it, or if there was a way to arbitrarily type-bound the generic.Shawn
01/25/2024, 9:07 PMShawn
01/25/2024, 9:11 PMsealed class ValidTypes {
class VtBool(val value: Boolean) : ValidTypes()
class VtInt(val value: Int) : ValidTypes()
}
fun doSomething(arg1: ValidTypes) {
when (arg1) {
is ValidTypes.VtBool -> {
}
is ValidTypes.VtInt -> {
}
}
}
Shawn
01/25/2024, 9:15 PMShawn
01/25/2024, 9:16 PMT & Any
), in order to support denoting a type as "definitely not nullable"Joffrey
01/25/2024, 9:17 PMwhen
branches are known statically anyway, it looks like you just need:
fun doSomething(arg1: Boolean) {
// whatever was in the Boolean branch of the when
}
fun doSomething(arg1: Int) {
// whatever was in the Int branch of the when
}
// other overloads for other branches
Garret Yoder
01/26/2024, 2:37 PMJoffrey
01/26/2024, 2:39 PMwhen
, so it's effectively multiple functions next to each other, just wrapped in a bit of boiler plate, which I personally think makes it harder to read, not easierGarret Yoder
01/26/2024, 2:44 PMShawn
01/26/2024, 4:45 PMfun <T> doSomething(arg1: T) {
when (arg1) {
is Boolean -> arg1.not()
is Int -> arg1.inc()
}
}
Shawn
01/26/2024, 4:46 PM