Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin secondary constructor with generic type

Tags:

kotlin

In java

I can achieve two constructors like

public TargetTitleEntryController() { }

public <T extends Controller & TargetTitleEntryControllerListener> TargetTitleEntryController(T targetController) {
        setTargetController(targetController);
}

I want to convert it to Kotlin

class TargetTitleEntryController ()

with the secondary constructor. I don't know how to declare with generic type like Java counterpart.

like image 515
Ken Zira Avatar asked Oct 15 '18 15:10

Ken Zira


1 Answers

There is no intersection types in Kotlin (sad)

But there is Generic constraints (hope)

But Generic constraints not applicable in the secondary constructor (sad)

But you can simulate secondary constructor in a companion object using Invoke operator overloading (workaround):

class TargetTitleEntryController {

    // ...

    companion object {

        operator fun <T> invoke(targetController: T): TargetTitleEntryController
                where T : Controller,
                      T : TargetTitleEntryControllerListener {
            return TargetTitleEntryController().apply {
                setTargetController(targetController)
            }
        }
    }
}
like image 169
tbrush Avatar answered Oct 16 '22 07:10

tbrush