Kotlin精明地使用过滤器投放配对的第二个值 [英] Kotlin smart cast the second value of a pair with filter

查看:62
本文介绍了Kotlin精明地使用过滤器投放配对的第二个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个映射String和Int的函数?成对,然后在继续映射之前过滤该对中的非null秒值.

I'm trying to write a function that maps a String and Int? into a pair, then filters for non null second values in the pair, before continuing to map.

我的代码如下:

val ids: List<String> = listOf("a", "b", "c")
val ints: Map<String, Int?> = mapOf("a" to 1, "b" to 2, "c" to null)

ids.map { id: String ->
    Pair(id, ints[id])
}.filter { pair -> pair.second != null}.map { pair: Pair<String, Int> ->
    func(id, pair.second)  
}

问题在于第二张地图有错误:

The problem is that the second map has the error:

Type inference failed: Cannot infer type parameter T in 
                       inline fun <T, R> kotlin.collections.Iterable<T>.map ( transform (T) -> R ): kotlin.collections.List<R>

这看起来像是因为编译器不知道将我的Iterable<Pair<String, Int?>>智能转换为我的filter之后的Iterable<Pair<String, Int>>.我该怎么办才能解决这个问题?

This looks like because the compiler does not know to smart cast my Iterable<Pair<String, Int?>> into an Iterable<Pair<String, Int>> after my filter. What can I do instead to solve this?

推荐答案

Kotlin的智能强制转换通常不适用于方法边界之外.但是,无论如何,有两种方法可以实现您的目标.

Kotlin's smart cast is usually not applicable outside method boundaries. However, there are a couple of ways you can achieve your goal anyway.

首先,您可以像这样使用!!运算符简单地告诉编译器该对的第二个值永远不会为空:

First, you can simply tell the compiler that the second value of the pair is never null by using the !! operator like so:

ids.map { id: String -> Pair(id, ints[id]) }
        .filter { pair -> pair.second != null }
        .map { pair: Pair<String, Int?> -> func(pair.second!!) }

第二,您可以颠倒filtermap的顺序,并更早地应用!!运算符:

Second, you can reverse the order of filter and map and apply the !! operator earlier:

ids.filter { id: String -> ints[id] != null }
        .map { id: String -> id to ints[id]!! } //equivalent to Pair(id, ints[id]!!)
        .map { pair: Pair<String, Int> -> func(pair.second) }

最后,通过使用mapNotNull扩展方法一步一步地将过滤和映射结合起来,可以使它在没有!!运算符的情况下工作:

Finally, you can make it work without the !! operator by combining the filtering and the mapping in one step using the mapNotNull extension method:

ids.mapNotNull { id: String -> ints[id]?.let { id to it } }
        .map { pair: Pair<String, Int> -> func(pair.second) }

这篇关于Kotlin精明地使用过滤器投放配对的第二个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆