A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name:

interface ControlTagType {
    type?: String | null;

    [name: string]: any
}

class ControlTag {
    tagSource: String | null = null;

    tag: ControlTagType | null = null;
}

export { ControlTag };

With this setup, I can use the class in vuejs like this:

controlTag.push({ tagSource: 'USER', tag: { type: 'X', TAG_1: 'TAG_X' } });
controlTag.push({ tagSource: 'AUTO', tag: { type: 'Y', TAG_2: 'TAG_Y' } });

This solution worked for another problem I had.

However, I'm struggling to achieve the same generic member functionality in kotlin:

I have an enum class that I utilize during serialization:

  @JsonValue
  fun value(): X {
    return X( this.name : this.name)
  }

like so:

data class X(val [name: string]: any)

I can do it this way, but it's complex and needs to be repeated for each class:

 @JsonValue
  fun value(): Any? {
    when (this.name) {
      XX_XX.name -> {
        return object {
          var XX_XX: String = name
        }
      }
      YY_YY.name -> {
        return object {
          var YY_YY: String = name
        }
      }
      ZZ_ZZ.name -> {
        return object {
          var ZZ_ZZ: String = name
        }
      }
      else -> return null
    }
  }

Furthermore, in this implementation, the parameter name is converted to lowercase:

{"type":"XX","xx_XX":"XX_XX"}

Answer №1

Index types do not exist in Kotlin.

However, you can utilize various implementations based on interfaces instead of using val[name: string]: any

interface ControlTagType {
  val type: String?
}

data class ControlTag(
    val tagSource: String? = null,
    val tag: ControlTagType? = null
)

data class FirstControlTagType(
    override val type: String? = null,
    val firstOne: String? = null
) : ControlTagType

data class SecondControlTagType(
    override val type: String? = null,
    val secondOne: String? = null
) : ControlTagType

Kotlin is designed to support multiple languages and constructions like val[name: string]: any, making it more dynamic compared to languages such as Java.

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

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

There is no overload that matches this call in Next.js/Typescript

I encountered a type error stating that no overload matches this call. Overload 1 of 3, '(props: PolymorphicComponentProps<"web", FastOmit<Omit<AnchorHTMLAttributes, keyof InternalLinkProps> & InternalLinkProps & { ...; ...

There is no correlationId found within the realm of node.js

Currently, I am in the process of implementing correlationId functionality using express-correlation-id. I am diligently following the guidelines provided on this page: https://www.npmjs.com/package/express-correlation-id. I have successfully imported the ...

Set up a personalized React component library with Material-UI integration by installing it as a private NPM package

I have been attempting to install the "Material-UI" library into my own private component library, which is an NPM package built with TypeScript. I have customized some of the MUI components and imported them into another application from my package. Howe ...

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

Retrieving text from a collection of Web Elements can be time-consuming

I have written a code to extract data from a web table, where each row is read as text and added to another list before being sent to a method for writing to an excel file. However, this process of reading approximately 200 rows and writing the data to a n ...

When I try to ng build my Angular 11 application, why are the type definitions for 'Iterable', 'Set', 'Map', and other types missing?

As someone new to Angular and the node ecosystem, I'm facing a challenge that may be due to a simple oversight. The issue at hand: In my Angular 11 project within Visual Studio 2019, configured with Typescript 4, attempting to run the project throug ...

What are the problems with Internet Explorer in Selenium WebDriver?

Currently dealing with a mouse-over issue in IE while using webdriver code. The functionality works smoothly in Chrome and Firefox, however, the problem arises only in IE. How can I resolve this? Initially focusing on an element and then clicking on a li ...

Selenium sendKeys isn't typing the desired text

Below is the code snippet that clicks on a button in a window. When the button is clicked, the current window closes and a new window opens. Text will be entered into a textbox in the new window. WebElement element=null; try { driver.g ...

Error in Docker: Unable to resolve due to sender error: context has been terminated

After attempting to build my docker image for the project in VS Code terminal, I ran into an error. What are some possible reasons for this issue? Along with this question, I have also shared a screenshot of the error logs. ERROR: failed to solve: error ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

TS7053: The element is implicitly assigned an 'any' type as the expression of type 'string' cannot be used to index the type '{ username: string; email: string; '

Having trouble incorporating TypeScript into a custom React Form Component, and I keep encountering an error that I can't seem to resolve. Error message TS7053: Element implicitly has an 'any' type because expression of type 'string&apo ...

The @Input directive is not compatible with the OnPush change detection strategy

page.html <app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost"> </app-parcel-delivery-cost-promo> page.ts changeDetection: ChangeDetectionStrategy.OnPush, parcelDeliveryCost: Partial<ParcelDeliveryCostModel>; ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...