I mean, strictly speaking it’d probably be somethi...
# announcements
s
I mean, strictly speaking it’d probably be something like
Copy code
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
Plain curiosity. And maybe
Copy code
holder.castTo(NetworkStateViewHolder).bindTo(networkState)
looks more fluid to me than
Copy code
(holder as NetworkStateViewHolder).bindTo(networkState)
Later is more idiomatic though.
And yes, it doesn’t work
s
fixed the syntax
in your case, usage would be
Copy code
holder.castTo<NetworkStateViewHolder>()
    .bindTo(networkState)
still don’t recommend it, but it works in my scratch file
t
Thanks, it works! Can you please elaborate on why you think it’s a bad idea? Apart from being not idiomatic?
s
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
Thanks for your help. Anyways, it helped me to learn something new about language features))
👍 1