Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

android - Get value from map in kotlin

I have a class :

Category(val name : String? = null, val products: Map<Product,Boolean> = mutableMapOf())

and this class is used in an activity in the map:

private var categoriesAndProducts = mutableMapOf<Category, Boolean>()

And my problem is when I have a name of the category, I need to go inside Category class and then outside to obtain category's boolean value. Problem is I don't know how to get this boolean value when I am inside. Like how to go back higher in this hierarchy and get that value.

question from:https://stackoverflow.com/questions/65862030/get-value-from-map-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understood you correct, you want to find a Category within categoriesAndProducts based on Category.name. Having this Category (which is the key), you then want to get it's Boolean value from categoriesAndProducts.

You can do this by filtering first for keys that are matching the Category name:

val key: Category? = categoriesAndProducts.keys.firstOrNull {
  it.name == "someName"
}

categoriesAndProducts[key] // returns null when key is null

You could write an extension function that helps you accessing the Category key based on a name:

fun Map<Category, Boolean>.findByName(name: String): Boolean? {
  val key: Category? = keys.firstOrNull { it.name == name }
  return get(key)
}

categoriesAndProducts.findByName("someName") // returns boolean

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...