Junior — Middle
How to implement a key-value storage in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the Map class is often used to store key-value pairs. If a mutable storage is needed, MutableMap is suitable.
Example of creating and using a mutable dictionary:
val map: MutableMap<String, Int> = mutableMapOf()
map["apple"] = 3
map["banana"] = 5
println(map["apple"]) // Will output 3
For Android, SharedPreferences is often used to store simple key-value pairs, such as app settings. Example of writing and reading:
val sharedPref = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
// Writing
with(sharedPref.edit()) {
putString("key", "value")
apply()
}
// Reading
val value = sharedPref.getString("key", "default")
Thus, for simple cases in Kotlin, you can use Map or MutableMap, and for storing settings in Android — SharedPreferences.