General casting in Kotlin

I have the following classes and interfaces:

public interface ActivityComponent<T extends Activity> {
    void inject(T activity);
}

public interface MyActivityComponent extends ActivityComponent<MyActivity> {
}

public abstract class DaggerActivity extends Activity {
    abstract ActivityComponent getComponent(Context context);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityComponent component = getComponent(this);
    }
}

public class MyActivity extends DaggerActivity {
    @Override
    ActivityComponent getComponent(Context context) {
        MyActivityComponent component = buildComponent();
        return component;
    }

And this is the same (I think?) Kotlin code:

public trait ActivityComponent<T : Activity> {
    public fun inject(activity: T)
}

public abstract class DaggerActivity : Activity {
    protected abstract fun getComponent(context: Context): ActivityComponent<Activity> // Type required

    override fun onCreate(savedInstanceState: Bundle?) {
        var component = getComponent(this)
    }
}

public class MyActivity extends DaggerActivity {
    override fun getComponent(context: Context): ActivityComponent<Activity> {
        val component: MyActivityComponent = buildComponent()
        return component as ActivityComponent<Activity>
    }
}

Note. The MyActivityComponent implementation is always in Java, so the Dagger can handle it.

The "problem" is that MyActivity.getComponent () in Kotlin requires dropping the return type, even if MyActivityComponentsubclassed ActivityComponent.

My understanding of Kotlin's generics is admittedly weak, and it's hard for me to translate from generics to Java. Can someone explain why this cast is necessary or, preferably, a correct implementation that eliminates the need for casting?

I also tried things like:

protected abstract fun <E : Activity> getComponent(context: Context): ActivityComponent<E>

and

protected abstract fun <A: Activity, E : ActivityComponent<A> getComponent(context: Context): E

With the same result (casting required).

+4
1

, Java ActivityComponent getComponent(). - Java, Java 5, Java 4.

. " ", .. ActivityComponent<*>, Java ActivityComponent<?>, .

, :

fun getComponent(context: Context): ActivityComponent<*>
+13

All Articles