https://kotlinlang.org logo
Title
s

Shawn

11/29/2018, 2:56 AM
I mean, strictly speaking it’d probably be something like
inline fun <reified T> Any.castTo() = this as T
but a) that probably won’t work, b) why do you need this as a function?
t

tyjka

11/29/2018, 3:02 AM
Plain curiosity. And maybe
holder.castTo(NetworkStateViewHolder).bindTo(networkState)
looks more fluid to me than
(holder as NetworkStateViewHolder).bindTo(networkState)
Later is more idiomatic though.
And yes, it doesn’t work
s

Shawn

11/29/2018, 3:15 AM
fixed the syntax
in your case, usage would be
holder.castTo<NetworkStateViewHolder>()
    .bindTo(networkState)
still don’t recommend it, but it works in my scratch file
t

tyjka

11/29/2018, 3:32 AM
Thanks, it works! Can you please elaborate on why you think it’s a bad idea? Apart from being not idiomatic?
s

Shawn

11/29/2018, 3:35 AM
mostly just that it’s not idiomatic, and that also if you’re ever in a situation where you’re okay with returning
null
if the class cast fails, you’ll just have to switch from the function to
(foo as? bar)?.baz()...
anyhow or add an additional
castToOrNull<>()
function
It’s just, kinda clumsy to replicate an existing language feature, but I suppose there’s nothing inherently bad about it
t

tyjka

11/29/2018, 4:21 AM
Thanks for your help. Anyways, it helped me to learn something new about language features))
👍 1