Inherit kotlin object from raw-type java object implicitly using upper bound

35 views Asked by At

I have:

class BaseActivity extends Activity { ... }

and i want to change it like this:

class BaseActivity<T extends BaseActivity<T>> { ... }

but i dont want to change all files in project

and in Java i can do:

class HomeActivity extends BaseActivity { ... }

yes i will get "Raw use of parameterized class 'BaseActivity'" warning but in kotlin i have to explicitly write a type:

class HomeActivity : BaseActivity<HomeActivity>() { ... }

or error will be "One type argument expected for class BaseActivity<T : BaseActivity<*>!>"

is there any option to make it work?

1

There are 1 answers

0
James Lan On

This trick is to allow the superclass to use the type of subclass.

For example, you could define fields/methods in BaseActivity<T> as

  List<T> siblings;
  void addSibling(T sibling);

then in your subclass HomeActivity which extends from BaseActivity<HomeActivity> will have typed members from the superclass,

  List<HomeActivity> siblings;
  void addSibling(HomeActivity sibling);

Using raw type causes the loss of types of these members.