What is the best way to store values in a map for future reference within a Kotlin class?

Looking to implement a map of key value pairs in Kotlin inside a class that is mutable and can be updated and referenced as needed. Research suggests that using a MutableMap would be the appropriate choice, given its ability to be updated at any point. In TypeScript, the code for this scenario would resemble the example below. How might one achieve similar functionality 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,
}

// perform an action later..
const doSomething = (streetName: string, callback: Callback): void => {
  dataMap.streetName = streetName;
  dataMap.callback = callback;
}

// followed by..
const printData = (): void => {
  console.log(dataMap.streetName) // prints the streetName
}

Answer №1

If your keys are dynamic, meaning the property names can change, then using a map would be necessary. Similarly, in TypeScript where you define specific property names in an interface, you can achieve the same in Kotlin.

An example code snippet in Kotlin could look like this:

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) // prints the streetName
}

It's generally advised to avoid using global variables whenever possible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The attribute 'XXX' is not found within the type 'IntrinsicAttributes & RefAttributes<any>'

My coding hobby currently involves working on a React website using TypeScript. I recently came across a free Material UI template and decided to integrate it into my existing codebase. The only challenge is that the template was written in JavaScript, cau ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Does anybody have information on the Namespace 'global.Express' not having the 'Multer' member exported?

While attempting to set up an endpoint to send a zip file, I keep encountering the following error: ERROR in ./apps/api/src/app/ingestion/ingestion.controller.ts:46:35 TS2694: Namespace 'global.Express' has no exported member 'Multer'. ...

Retrieve parent route parameters from a dynamically loaded route component

Struggling to access the parent route params in a lazy loaded route component using activatedRoute.parent.params. Despite this not working, I have managed to find a solution that involves fetching the value using an array index number which feels like a &a ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

getting TypeScript configured with webpack

I am currently using Typescript to develop a back-end API utilizing graphql and express. To manage the project development and building process, I have implemented webpack. As part of my setup, I am employing raw-loader in order to load graphql schemas an ...

Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error. const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td> ...

Is it possible to modify the Angular global error handler to accept additional parameters besides just the error object?

After exploring the capabilities of https://angular.io/api/core/ErrorHandler, I have found that it allows me to override the global error handler with an error object. I appreciate how I can easily define my own global error handler and use it wherever nec ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

Tips on showcasing an array as a matrix with a neat line property

I am currently developing an application using TypeScript, and utilizing a JSON array structured like this: data = [{"name":"dog", "line":1}, {"name":"cet", "line":1}, ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

Stop committing changes in Git when there are any TypeScript errors found

While working on my project in TypeScript using Visual Code, I encountered a situation where I was able to commit and push my changes to the server through Git (Azure) even though there was an error in my code causing a build failure. It made me wonder i ...

Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance. During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. ...

Exploring ways to list interface keys in order to create a new interface where the value is determined by the corresponding key

How can we iterate through interface keys to create a new interface where the value is dependent on the key? type IParse<T> = { [K in keyof T as K extends string ? K : never]: string // How can we specify that if K === 'a', the type sho ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...

Guide on specifying the return type of a generic class when using TypeScript

The code I am working with is structured like this: import * as events from 'events' // Utilizing Node.js events module // My custom implementation of EventEmitter with enhanced typing interface IEventEmitter<EventTypes> { /* ... */ } // ...

Generating data types based on the output of functions

I'm currently working on optimizing my typescript react code by reducing repetition. I'm curious to know if there's a way to generate a type based on the return type of a known function? For example: const mapStateToProps = (state: StoreSt ...

Unit testing Angular components can often uncover errors that would otherwise go unnoticed in production. One common

I need assistance writing a simple test in Angular using Shallow render. In my HTML template, I am utilizing the Async pipe to display an observable. However, I keep encountering the following error: Error: InvalidPipeArgument: '() => this.referenc ...