Hey folks, I might be missing something, but why I...
# announcements
a
Hey folks, I might be missing something, but why IDE is not complaining about unsafe cast if following snippet?
Copy code
val nullableList: List<String>? = listOf()
val nonNullableList: List<String> = nullableList as List<String>
p
why should it?
Casting is always kind of unsafe, do you think it should always warn you when you cast?
a
Doing a cast is always "unsafe" IIRC there's an "unsafe cast" warning in the java world which has to do with generics, (the cast itself will work because of type erasure but) down the line you'll get ClassCastException (or something) while in the source code it doesn't look like you're casting anything Not sure if kotlin has such a warning too
p
These kind of unsafe casts you get warned about by kotlin too
It's for example if you cast a
List<String?>
to a
List<String>
👍 1
a
I'm guessing that happens when you do
Copy code
val x: List<String?> = listOf()
val y: List<String> = x as List<String>
p
Yes
And that gives no error at runtime because it's both a list
As you don't have generics in bytecode
And that puts you in a realllllyyy weird state
Like
Copy code
fun main() {
    val intList = mutableListOf<Int>()
    intList.add(1)
    (intList as MutableList<String>).add("hello")
    println(intList)
}
[1, hello]
🧌
a
Hm, yes, it’s not about
List
. Cast in general is unsage:
Copy code
val string: String? = "ha"
val nonNullString: String = string as String
p
That's not unsafe because you explicitly cast and that at least fails at runtime
a
If it’s explicit in a similar way as
!!
then I’d rather prefer having
as!!
operator
a
there's
as?
to do a "safe" cast
There are probably linters with an option to warn you about casting if you feel like you want warnings
p
@armaxis that's noise, then you always need to have
as!!
?
a
My point is that I noticed a mistake made by a person who recently picked Kotlin and there was no warning about it. There was
val list = payload.data?.items as List<Items>
and null-safety got lost here.
p
Raise the :
Kotlin | Probable bugs | Implicit (unsafe) cast from dynamic type
a
if the syntax would've been
as!!
then the code probably would've been written as
val list = payload.data?.items as!! List<Items>
...
a
Kotlin | Probable bugs | Implicit (unsafe) cast from dynamic type
didn’t complain in this:
Copy code
val string: String? = "ja"
val nuString: String = string as String
b
i assume because it’s statically provable that
string
is not null at that point in the program?
what if instead of
"ja"
you use
null
a
@Ben Madore same thing - no warnings
l
Then that's an issue to report on kotl.in/issue