https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

03/11/2024, 2:29 AM
Copy code
private fun cast(arguments: List<*>): List<String> {
        if (arguments.all { it is String })
            return arguments as List<String>
    }
Unchecked cast: List<*> to List<String> what?
j

Jacob

03/11/2024, 2:44 AM
Makes sense to me. It might be a list ANY that happens to at the moment only contain strings
It might be an empty list
If you want you can do
arguments.map{it as? String}.
That will get you a list STRING
r

Ray Rahke

03/11/2024, 3:04 AM
if it is an empty list then the all { it is String } would fail , no?
e

ephemient

03/11/2024, 3:08 AM
the type checker doesn't know what
all
does
and in general
List
could be a view of some mutable list, so its items could change on another thread in between the
all
check and the
as
cast, making it unsafe
3
💯 1
a

AdamW

03/11/2024, 3:19 AM
Copy code
fun cast(input: List<*>) {
  println(input.all { it is String })
}
cast(emptyList<Int>())
cast(listOf<Int>())

=> 
true
true
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/all.html > Note that if the collection contains no elements, the function returns true because there are no elements in it that do not match the predicate
e

ephemient

03/11/2024, 3:20 AM
that too, but emptyList is also a special singleton :)
I meant like
Copy code
val list = CopyOnWriteArrayList()
list.add("1")
thread { list.add(2) }
cast(list)
means the unchecked cast is unsafe
now depending on what you want, there is
Copy code
list.filterIsInstance<String>()
or
Copy code
list.mapNotNull { it as? String }
which will discard non-string items, or
Copy code
list.map { it as String }
which will throw (and you can adjust that to whatever you need of course)
3