Branislav
Branislav

Reputation: 55

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.

Upvotes: 1

Views: 1078

Answers (1)

ChristianB
ChristianB

Reputation: 2680

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

Upvotes: 1

Related Questions