Computer scienceProgramming languagesKotlinObject-oriented programmingGenerics

Variance

Star Wars androids

Report a typo

Luke Skywalker is coding an app to manage androids. Could you please complete the Republic class to handle a list of androids with variance options? We can ensure that we can treat Republic<AstromechDroid> and Republic<ProtocolDroid> as their respective types or their common supertype (Android) when retrieving the lists of androids.

open class Android(val name: String)

class AstromechDroid(name: String) : Android(name) {
    fun repair() {
        println("Repairing a starship")
    }
}

class ProtocolDroid(name: String) : Android(name) {
    fun translate() {
        println("Translating languages")
    }
}

class Republic
/* write your code here */
(val androids: List<T>)  
{
    fun getAndroids(): List<T> {
        return androids
    }
}

fun main() {
    val astromechDroids = listOf(AstromechDroid("R2-D2"), AstromechDroid("BB-8"))
    val protocolDroids = listOf(ProtocolDroid("C-3PO"), ProtocolDroid("D-O"))

    val republicAstromechs: Republic<AstromechDroid> = Republic(astromechDroids)
    val republicProtocols: Republic<ProtocolDroid> = Republic(protocolDroids)

    val astromechList: List<AstromechDroid> = republicAstromechs.getAndroids()
    val protocolList: List<ProtocolDroid> = republicProtocols.getAndroids()

    for (astromech in astromechList) {
        println("Astromech Droid name: ${astromech.name}")
        astromech.repair()
    }

    for (protocol in protocolList) {
        println("Protocol Droid name: ${protocol.name}")
        protocol.translate()
    }
}
Enter a short text

Create a free account to access the full topic