Was making `is`/`as` functions instead of language...
# language-evolution
b
Was making `is`/`as` functions instead of language features ever considered? (similar to how Java casting went that direction, and how there's a general preference for not introducing language features when it can be done another way. Or even making them soft keywords so functions could be introduced I could see it being done like this, with contracts to enable smart casting/etc:
Copy code
x.is<String>()
x.isNot<String>()
x.as<String>()
x.asOrNull<String>()
For one I think it would make chaining nicer. There are definitely times when I do
.let { it as String }
on its own line in the middle of a big chain of calls, and was tempted to wrote my own
fun <T> Any?.as(): T
but got dissuaded when I need to write `.`as`<...>()`. Mostly just a curiosity though :)
y
in some Kotlin compiler internal code, there is a file called
addToStdlib.kt
which includes some extensions that are used in that internal code, amongst them is
cast
and
safeCast
which function as you'd expect, and so even some JB folks might agree that those functions can be useful. Personally, I don't think is and as should be functions by default, but I'd love if the stdlib had
cast
and
safeCast
👀 1
e
C++ is also a function,
dynamic_cast<T>()
(well really a collection of functions, because they have many types of casts)
but if you're willing to take a different syntax, we do functions in Kotlin already:
Copy code
String::class.isInstance(x)
String::class.cast(x)
String::class.safeCast(x)
d
We are considering adding functions like
cast<T>()
and
safeAs<T>()
for simplifying chain calls, but they require compiler support, because without it compiler won't report warnings about definitely unsafe casts, which may lead to errors in code
Copy code
"" as Int // CAST_NEVER_SUCCEED warning
"" as? Int // CAST_NEVER_SUCCEED warning
"".cast<Int>() // no warning
"".safeAs<Int>() // no warning
👀 2
As for
is
and
notIs
functions, there is no much sense in them, because usually boolean expressions are not used in chain calls, and
is/!is
syntax looks much more readable then function calls
1
z
Dimitry, could that compiler support be in the form of contracts? Then you could write, eg, cast operators for lists/flows that would generate the same warnings.
👆 1
d
We didn't discussed it yet
s
wouldn’t
castOrNull
be more idiomatic/consistent than
safeCast
?
☝️ 1
d
Maybe. As I said before, we didn't designed it
👍 3