Aside: I wished we had something like: ```fun <...
# plugin-development
k
Aside: I wished we had something like:
Copy code
fun <T, U : T> Provider<T>.cast(subclass: KClass<U>): Provider<U>
in the Kotlin APIs.
v
Would you win much from such an extension method? Should be
Copy code
foo.cast(Bar::class)
vs.
Copy code
foo.map { it as Bar }
k
It doesn't add much in the grand scheme of things - it's kind of "filter by type" sugar (ie. return an absent provider if the provided object isn't of a specified type)
Backed by
KClass.safeCast()
, of course.
v
return an absent provider if the provided object isn't of a specified type
Well, then
Copy code
foo.map { it as? Bar }
?
k
Basically yes -
as?
, but generic.
v
I still don't get it. What would be better if you do
Copy code
foo.castOrNull(Bar::class)
instead of directly doing
Copy code
foo.map { it as? Bar }
?
k
Nothing, just syntactic sugar.
v
So you find the first sweeter? o_O I like the second more. 😄
j
I would like to have this on the stdlib with compile checks
Copy code
foo.castOrNull<Bar>()
v
That's not possible, you need to give both type arguments in that case like you see in the
baz
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.
j
both type arguments
Why? you only need the output one, no?
v
No
Either all inferred or all given explicitly
k
To add to this: unless you had
Copy code
inline 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.
v
How would that help? The point is that you not cast
X
to
Y
but
Provider<X>
to
Provider<Y>
, so you have
X
and
Y
and have to specify or infer both
k
I was only merely stating some ways that you could hard-wire
Any
to reduce the number of type arguments. Not that it's any better.