Mike M
Mike M

Reputation: 3

Kotlin - pass dynamic type to a method

I have a method in kotlin (I will use a simple version here)

  private fun checkMissing(input: InputType) {
    input.name=do something
    }

I have 2 classes: InputType and InputType1.

 data class InputType1(
 override var name: String?,
  ..
 ): ExternalClass

 data class InputType1(
 override var name: String?,
  ..
 ): ExternalClass

InputType1 and InputType2, have a common field name,that I want to reassign, but the rest of the input is different. In my checkMissing method, I want to be able to pass InputType1 from one method call, and inputType2, from another method.

 fun method1(input: InputType1) { checkMissing(input)-> I want this to mutate the input values of InputType1 else }
 fun method2(input2: InputType2) {checkMissing(input2)-> here the same //smth else}

Is there a way to do it, without creating checkMissing separately for both input types? As the method will need to override input.name in both InputTypes classes accordingly.

Upvotes: 0

Views: 1356

Answers (2)

Tenfour04
Tenfour04

Reputation: 93571

Make an interface that they both implement. (Alternatively, this could be an open, abstract, or sealed class instead of an interface.)

interface InputType {
    val name: String?
}

data class InputType1: InputType(
    override var name: String?,
    //...
)

Then make the parameter type of the checkMissing function the interface.

private fun checkMissing(input: InputType) {
    //do something with input.name
}

Upvotes: 3

Adam Millerchip
Adam Millerchip

Reputation: 23091

If you want to ensure that you always get either an InputType or an InputType1 and nothing else, you can use a sealed class:

sealed class Input(open var name: String?)
data class InputType(override var name: String?) : Input(name)
data class InputType1(override var name: String?) : Input(name)

fun checkMissing(input: Input) {
    println(input.name)
}

Upvotes: 0

Related Questions