Kelvin Chung
10/16/2024, 7:08 PMfun <T, U : T> Provider<T>.cast(subclass: KClass<U>): Provider<U>
in the Kotlin APIs.Vampire
10/16/2024, 9:37 PMfoo.cast(Bar::class)
vs.
foo.map { it as Bar }Vampire
10/16/2024, 9:45 PMKelvin Chung
10/16/2024, 9:46 PMKelvin Chung
10/16/2024, 9:47 PMKClass.safeCast(), of course.Vampire
10/16/2024, 9:49 PMreturn an absent provider if the provided object isn't of a specified typeWell, then
foo.map { it as? Bar }
?Kelvin Chung
10/16/2024, 9:52 PMas?, but generic.Vampire
10/16/2024, 9:55 PMfoo.castOrNull(Bar::class)
instead of directly doing
foo.map { it as? Bar }
?Kelvin Chung
10/16/2024, 10:04 PMVampire
10/16/2024, 10:05 PMJavi
10/17/2024, 3:05 PMfoo.castOrNull<Bar>()Vampire
10/17/2024, 3:08 PMbaz line of my screenshot.
And if you use "treat warnings as errors" which I usually do in Kotlin projects, foo.map { it as? Bar } will also not compile if Bar can never succeed.Javi
10/17/2024, 3:17 PMboth type argumentsWhy? you only need the output one, no?
Vampire
10/17/2024, 3:27 PMVampire
10/17/2024, 3:28 PMKelvin Chung
10/17/2024, 3:31 PMinline fun <reified U> Any.castOrNull(obj: Any?) = U::class.castOrNull(obj)
you'd be defining a method taking in two or more type arguments. So you'd need to specify all of them, even if it has to be underscores.Vampire
10/17/2024, 3:32 PMX to Y but Provider<X> to Provider<Y>, so you have X and Y and have to specify or infer bothKelvin Chung
10/17/2024, 3:34 PMAny to reduce the number of type arguments. Not that it's any better.