https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

mbonnin

02/21/2024, 11:08 AM
Could we have
inline fun <reified T : Any> Any?.cast(): T = this as T
in the stdlib? It's been in addToStdLib.kt for a while but looks like it's now deprecated? Is there a fundamental reason this is not possible?
2
👍🏼 1
d

dmitriy.novozhilov

02/21/2024, 11:12 AM
There is a reasoning described in the same file
Copy code
Usage of this function is unsafe because it does not have native compiler support
This means that compiler won't report UNCHECKED_CAST, CAST_NEVER_SUCCEED or similar diagnostics in case of error cast (which can happen immediately or after some refactoring of class hierarchy)
Consider using regular `as` and `as?`
m

mbonnin

02/21/2024, 11:22 AM
This is what I'm not getting. The function is doing the same thing as what I would normally do from my code. Am I missing on diagnostics when doing this myself?
And follow up question is could compiler support be added?
d

dmitriy.novozhilov

02/21/2024, 11:23 AM
This function allow such code to be compiled without any warnings/errors
Copy code
"hello".as<Int>()
👍🏾 1
👍 5
m

mbonnin

02/21/2024, 11:23 AM
Ahhh yes, I see 👍
d

dmitriy.novozhilov

02/21/2024, 11:24 AM
And follow up question is could compiler support be added?
It could, but it's not on the table right now
m

mbonnin

02/21/2024, 11:24 AM
Gotcha 👍
Thanks for the insights!
👌 1
a

andylamax

02/21/2024, 11:25 AM
Yes, thats some good insight