Nexicoll
Nexicoll

Reputation: 27

Pass class object to function (Kotlin)

Sorry if this is stupid question, but I can resolve that

I have two classes

class A(
    val id: Int
)

class B(
    val id: Int,
    val className: String
)

Now I want to pass one of the object to function. I want to make "uniwersal" function.At the moment I have to make 2 function.

One with argument type as A

fun printClassFields(classObject: A){

}

And second with argument B

fun printClassFieldsB(classObject: B){

}

Is possible to make one function which accept both classes ?

Upvotes: 0

Views: 1526

Answers (1)

patrick.elmquist
patrick.elmquist

Reputation: 2140

It's a bit unclear what you want to do with the classes inside the function, but here are some options.

You could use an interface for all common fields:

interface Common {
    val id: Int
}
class A(
    override val id: Int
) : Common

class B(
    override val id: Int,
    val className: String
) : Common

fun print(obj: Common) {
    print(obj.id)
}

Another solution, if you know all the types, is to hardcode the function like:

fun print(obj: Any) {
    when (obj) {
        is A -> { /* handle class A */ }
        is B -> { /* handle class B */ }
    }
}

Here you'll get the Smart Cast from Kotlin and will have access to the fields of each class. However you open the function up to be called with anything as input which may not be desirable.


Another option is to use a Sealed Class, where you get the Smart Cast but limit the parameter type.

sealed class SealedSuper(val id: Int)
class A(id: Int) : SealedSuper(id)
class B(id: Int, val className: String) : SealedSuper(id)

fun print(obj: SealedSuper) {
    when (obj) {
        is A -> { 
            print(obj.id)
        }
        is B -> {
            print(obj.id)
            print(obj.className)
        }
    }
}

Upvotes: 2

Related Questions