如何在访问Kotlin中HashMap中声明的对值时删 debugging 误“Create extension property'Any.second'?

nom7f22z  于 2023-10-23  发布在  Kotlin
关注(0)|答案(1)|浏览(75)

我有一个名为ImageStore的Singleton类,其中我声明了一个Hashmap,其中每个键的值都是一个Pair,如下所示

object ImageStore {

    val imagesNamesMap = hashMapOf(
        R.drawable.africa to Pair("Africa","Afrika"),
        R.drawable.asia to Pair("Asia","Azija"),
        R.drawable.europe to Pair("Europe","Europa"),
        R.drawable.antartica to Pair("Antarctica","Antarktida"),
        R.drawable.airplane to Pair("Aeroplane","Lėktuvas"),
        R.drawable.apple1 to Pair("Apple","Obuolys"),
        R.drawable.key to Pair("Key","raktas"),
        R.drawable.sleep to Pair("to sleep","miegoti)"
    ).toList().shuffled().take(4)).toMap()

}

我有一个Fragment,我试图访问Imagestore的示例和Pair中的两个值,所以我把这段代码放在我的Fragment类中,如下所示。

val shuffledImageResources = ImageStore.imagesNamesMap.keys.toList().shuffleList().toMutableList()

        val shuffledImageNames1: List<Pair<String, String>> = shuffledImageResources.mapNotNull { it ->
            val pair = ImageStore.imagesNamesMap[it]
            pair?.let { Pair(pair.first, pair.second) } //
        }

这里firstsecondfrom pair.first和pair.second在我单击firstfrom pair.first时给出错误。它给予以下消息,如下图所示

2https://i.stack.imgur.com/Vo94H.jpg和当我点击第二从对.第二,它给我这个错误,如下图所示

fslejnso

fslejnso1#

imagesNamesMap中的值的推断类型是Any,而不是Pair。请尝试以下操作:

val imagesNamesMap = hashMapOf(
    R.drawable.africa to Pair("Africa","Afrika"),
    R.drawable.asia to Pair("Asia","Azija"),
    R.drawable.europe to Pair("Europe","Europa"),
    R.drawable.antartica to Pair("Antarctica","Antarktida"),
    R.drawable.airplane to Pair("Aeroplane","Lėktuvas"),
    R.drawable.apple1 to Pair("Apple","Obuolys"),
    R.drawable.key to Pair("Key","raktas"),
    R.drawable.sleep to Pair("to sleep","miegoti")
).toList().shuffled().take(4).toMap()

我删除了take(4)之后的),并将Pair("to sleep","miegoti)"中的)"交换

相关问题