Ragunath Jawahar
Ragunath Jawahar

Reputation: 19723

Multiple inheritence in Kotlin

Consider the following example

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(Bundle?: savedInstanceState) {
        super<Activity>.onCreate(savedInstanceState)

        ...

        someButton.setOnClickListener(this) // How do I refer to the `OnClickListener` implementation?
    }
}

How do I refer to the OnClickListener implementation in the above mentioned code snippet?

Upvotes: 1

Views: 3665

Answers (2)

Jayson Minard
Jayson Minard

Reputation: 85936

Not wanting to create an Android project, I created a mock up of your classes and there are no errors using the code mentioned in another answer:

// mocked up classes

interface Bundle {}

open class Activity {
    open fun onCreate(savedInstanceState: Bundle?) {}
}
interface View {}

interface OnClickListener {
    fun onClick(v: View)
}

open class Button(a: Activity) {
    fun setOnClickListener(o: OnClickListener) {}
}

// the usage, showing no error:

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super<Activity>.onCreate(savedInstanceState)

        val someButton = Button(this)

        someButton.setOnClickListener(this) // NO ERROR
    }

    override fun onClick(v: View) {
        // TODO implement
    }
}

Upvotes: 0

user2235698
user2235698

Reputation: 7579

Don't forget to implement onClick(View) function and change onCreate signature. After that code will looks like below:

public class SomeActivity() : Activity(), OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super<Activity>.onCreate(savedInstanceState)

        val someButton = Button(this)

        someButton.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        // TODO implement
    }
}

Upvotes: 2

Related Questions