is there a way to accept an argument that is either of type a or b in kotlin?

Sealed classes do pretty much that:

sealed class AorB (val common : String)
class A(val a: String, common: String) : AorB(common)
class B(val b: String, common: String) : AorB(common)

fun accept(param: AorB) {
    when(param) {
        is A -> println(param.a)
        is B -> println(param.b)

fun main() {
    accept(A("a value", "common value")) 
    accept(B("b value", "common value")) 

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top