Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 为每个循环键入cast-in_Loops_Generics_Kotlin_Iterator - Fatal编程技术网

Loops 为每个循环键入cast-in

Loops 为每个循环键入cast-in,loops,generics,kotlin,iterator,Loops,Generics,Kotlin,Iterator,我正在重构一些代码,作为中间步骤,我想迭代X列表,并将每个元素类型转换为Y。 以下工作: val xs: List<X> for (x in xs) { val y = x as Y } 没有任何成功。 甚至可以将类型转换和迭代结合起来吗?如何操作?您可能希望执行以下操作: xs.map {it as Y}.forEach { //do your stuff } forEachCasted<Y>(xs) { ... }

我正在重构一些代码,作为中间步骤,我想迭代
X
列表,并将每个元素类型转换为
Y
。 以下工作:

val xs: List<X>
for (x in xs) {
    val y = x as Y
}
没有任何成功。
甚至可以将类型转换和迭代结合起来吗?如何操作?

您可能希望执行以下操作:

xs.map {it as Y}.forEach { 
            //do your stuff
        }
forEachCasted<Y>(xs) { ... }

我认为这是一种非常好的语法,不需要任何额外的变量

您可以通过转换到高阶函数来提取
forEach

inline fun <reified T> forEachCasted(iterable: Iterable<*>, action: (T) -> Unit) =
    iterable.forEach { action(it as T) }
inline fun <reified T> Iterable<*>.forEachCasted(action: (T) -> Unit) =
    forEach { action(it as T) }
并以这种方式使用它:

xs.forEachCasted<Y> { ... }
xs.forEachCasted{…}
您是否尝试过使用该功能?您可以将每个元素映射到其强制转换形式,并遍历映射的集合。我现在不能尝试它,但是类似这样的东西:
for(y in xs.map{it as y})
使用
Iterable#map
可以创建一个新的集合。因此,如果
xs
包含大量元素,则会对性能产生不利影响。
xs.forEachCasted<Y> { ... }