for-each循环中的类型转换

问题描述 投票:0回答:2

我正在重构一些代码,作为中间步骤,我想遍历X的列表,然后将每个元素类型强制转换为Y。以下作品:

val xs: List<X>
for (x in xs) {
    val y = x as Y
}

但是我想知道如何结合迭代和类型转换,以便1)我不必引入变量x和2)我可以将两行合并为一行。

我尝试了以下内容

val xs: List<X>
for ((y as Y) in xs) {
}

val xs: List<X>
for ((y in xs) as Y) {
}

没有任何成功。甚至可以将类型转换和迭代结合起来吗?怎么样?

loops generics kotlin iterator
2个回答
1
投票

您可能想做这样的事情:

xs.map {it as Y}.forEach { 
            //do your stuff
        }

我想说这是一个很好的语法,不需要任何其他变量


0
投票

您可以通过强制转换为高阶函数来提取forEach

inline fun <reified T> forEachCasted(iterable: Iterable<*>, action: (T) -> Unit) =
    iterable.forEach { action(it as T) }

并像这样使用它:

forEachCasted<Y>(xs) { ... }

或者,您可以使forEachCasted成为扩展功能:

inline fun <reified T> Iterable<*>.forEachCasted(action: (T) -> Unit) =
    forEach { action(it as T) }

并以这种方式使用:

xs.forEachCasted<Y> { ... }
© www.soinside.com 2019 - 2024. All rights reserved.