Reputation: 1824
I want to create a map of key value pairs in Kotlin inside a class that can be arbitrarily updated and referenced. I have read that a MutableMap may be what I need since I can update is at any time. In Typescript my code would look like the following. How can I write something similar in Kotlin?
type Callback = (id: string) => void | null;
interface DataMap {
streetNumber: number | null;
streetName: string | null;
callback: Callback | null;
}
const dataMap: DataMap = {
streetNumber: null,
streetName: null,
callback: null,
}
// do something later..
const doSomething = (streetName: string, callback: Callback): void => {
dataMap.streetName = streetName;
dataMap.callback = callback;
}
// and then..
const printData = (): void => {
console.log(dataMap.streetName) // streetName is printed
}
Upvotes: 0
Views: 236
Reputation: 37710
You only need a map if the keys themselves are dynamic (the names of the properties). If in TS you have an interface with specific property names, you can do the same in Kotlin.
A somewhat equivalent code in Kotlin could be:
typealias Callback = (id: String) -> Unit?
data class DataMap(
var streetNumber: Int?,
var streetName: String?,
var callback: Callback?,
)
val dataMap = DataMap(
streetNumber = null,
streetName = null,
callback = null,
)
// do something later..
fun doSomething(streetName: String, callback: Callback) {
dataMap.streetName = streetName
dataMap.callback = callback
}
// and then..
fun printData() {
println(dataMap.streetName) // streetName is printed
}
Although we would usually avoid global variables.
Upvotes: 2