Extend and implement at the same time in Kotlin

JavaKotlin

Java Problem Overview


In Java, you can do such thing as:

class MyClass extends SuperClass implements MyInterface, ...

Is it possible to do the same thing in Kotlin? Assuming SuperClass is abstract and does not implement MyInterface

Java Solutions


Solution 1 - Java

There's no syntactic difference between interface implementation and class inheritance. Simply list all types comma-separated after a colon : as shown here:

abstract class MySuperClass
interface MyInterface

class MyClass : MySuperClass(), MyInterface, Serializable

Multiple class inheritance is prohibited while multiple interfaces may be implemented by a single class.

Solution 2 - Java

This is the general syntax to use when a class is extending (another class) or implementing (one or serveral interfaces):

class Child: InterfaceA, InterfaceB, Parent(), InterfaceZ

Note that the order of classes and interfaces does not matter.

Also, notice that for the class which is extended we use parentheses, thee parenthesis refers to the main constructor of the parent class. Therefore, if the main constructor of the parent class takes an argument, then the child class should also pass that argument.

interface InterfaceX {
   fun test(): String
}

open class Parent(val name:String) {
    //...
}

class Child(val toyName:String) : InterfaceX, Parent("dummyName"){

    override fun test(): String {
        TODO("Not yet implemented")
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchntgomezView Question on Stackoverflow
Solution 1 - Javas1m0nw1View Answer on Stackoverflow
Solution 2 - JavaMr.QView Answer on Stackoverflow