``` private fun cast(arguments: List<*>):...
# getting-started
r
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
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
if it is an empty list then the all { it is String } would fail , no?
e
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
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
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