Ray Rahke
03/11/2024, 2:29 AMprivate fun cast(arguments: List<*>): List<String> {
if (arguments.all { it is String })
return arguments as List<String>
}
Unchecked cast: List<*> to List<String>
what?Jacob
03/11/2024, 2:44 AMJacob
03/11/2024, 2:44 AMJacob
03/11/2024, 2:47 AMarguments.map{it as? String}.
Jacob
03/11/2024, 2:48 AMRay Rahke
03/11/2024, 3:04 AMephemient
03/11/2024, 3:08 AMall
doesephemient
03/11/2024, 3:11 AMList
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 unsafeAdamW
03/11/2024, 3:19 AMfun 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 predicateephemient
03/11/2024, 3:20 AMephemient
03/11/2024, 3:23 AMval list = CopyOnWriteArrayList()
list.add("1")
thread { list.add(2) }
cast(list)
means the unchecked cast is unsafeephemient
03/11/2024, 3:24 AMlist.filterIsInstance<String>()
or
list.mapNotNull { it as? String }
which will discard non-string items, or
list.map { it as String }
which will throw (and you can adjust that to whatever you need of course)