Home > database >  Set property type from specific class as parameter type
Set property type from specific class as parameter type

Time:06-07

I have this sample data class:

data class Car ( var id: String )

Now I can create a fun as this:

fun doWhatever(id: String){}

My problem is that if my customer then tells me that Id is an int, I have to change it in both places. So what I want is to set Car.id type as refence in fun doWhatever, something like this:

fun doWhatever(id: propertyTypeOfCarId){}

So I if the customer changes type, I only have to change it in the class.

I read all kind of posts, but I wasnt able to find the answer. Any idea how to achieve it?

CodePudding user response:

If the number of id types you support is limited, you can simply use method overloading:

fun doWhatever(id: String){}

fun doWhatever(id: Int){}

// etc.

Alternatively, you can use a reified generic parameter in your method to support any number of types:

inline fun <reified T> doWhatever(id: T) {
  when (T::class) {
    Int::class -> {}
    String::class -> {}
  }
}

CodePudding user response:

If this isn't something you expect to be doing regularly, consider just using the refactoring tools the IDE provides. You code to handle a specific set of data, and if the structure of that data changes, you have to adapt the code to fit it. Baking in a bunch of "what if" functionality can add complexity, compared to just saying a String is a String and changing it if it ever needs changing, using the tools provided to make that as quick and easy as possible.


But sometimes you need to do this kind of thing, and Kotlin has some nice language features it can be worth using, like type aliases:

typealias CarId = String

data class Car(var id: CarId)

fun doWhatever(id: CarId){}

Two benefits here: the actual type is only defined in one place, so you can change that String to an Int without needing to change anything else - except stuff that relied on the ID being a String specifically of course

The other benefit is you're actually adding some semantic information by using that very specific type. That function isn't supposed to just take any old String - it's specifically meant to handle CarIds. It tells you what it's for, and that can make your code a lot easier to understand

(The function will accept Strings, because CarId is just an alias - an alternative name for a String - so it's not a way to enforce structure on your code, just a way to make it nicer to read and write. You can't define a new type that is a String in Kotlin unfortunately)

  • Related