https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

03/01/2023, 8:40 AM
I’ve got some function that can take one of several different classes, including classes that were defined outside of my code, but nothing other than those. let’s say it accepts
Int
,
Boolean
and
MyClass
. I want to be able to exhaustively check which underlying class it is, and then use the underlying class. so I need to be able to statically enumerate all possible classes. my current solution looks like
Copy code
sealed class Wrapper<out T> {
    abstract val value: T

    class Int(override val value: <http://kotlin.Int|kotlin.Int>) : Wrapper<kotlin.Int>()
    class Boolean(override val value: kotlin.Boolean) : Wrapper<kotlin.Boolean>()
    class MyClass(override val value: MyClass) : Wrapper<MyClass>()

    // ...
}
is there a better way to do this, or a way to reduce the boilerplate? ideally I’d like some way to add another case, and “automatically” generate a variant for this class.
m

Michael de Kaste

03/01/2023, 9:34 AM
unless I misunderstand your question, you can't really use sealed classes combined with variants defined outside your code unless you manually add those in.
👍 1
a

Adam S

03/01/2023, 9:35 AM
do you need a wrapper class, or would creating function overloads for each argument type also work? So you'd have
Copy code
fun myFunction(value: Int) { }
fun myFunction(value: Boolean) { }
fun myFunction(value: MyClass) { }
y

y

03/01/2023, 9:38 AM
@Adam S the code originally had function overloads, but I didn’t like that solution. the wrapper value was part of an
interface
, so it had to keep repeating
override fun myFunction(...)
for each interface implementation. it meant adding another variant needed a new overload in each implementation, and the changes were not local to one area of the code