0

I have two classes:

BaseViewModel extends ViewModel

NetworkViewModel extends BaseViewModel

In Kotlin I can use this method:

override fun selectViewModel(): Class<BaseViewModel> {
    return NetworkViewModel::class.java as Class<BaseViewModel>
}

But in Java I can´t do this (incompatible types):

@Override
public Class<BaseViewModel> selectViewModel() {
    return NetworkViewModel.class;
}

In Kotlin I can use "as", but how to do it in Java?

Michalsx
  • 3,446
  • 5
  • 33
  • 46
  • 4
    Shouldn't the return type be `Class extends BaseViewModel>`? – khelwood Dec 03 '19 at 14:14
  • Possible duplicate of [Is there any keyword in Java which is similar to the 'AS' keyword of C#](https://stackoverflow.com/questions/6219773/is-there-any-keyword-in-java-which-is-similar-to-the-as-keyword-of-c-sharp) – Syed Ahmed Jamil Dec 03 '19 at 14:15
  • i think you can use the `instanceof` keyword – diAz Dec 03 '19 at 14:18
  • @diAz `instanceof` becomes `is` in Kotlin and is meant to check whether a specific object "is a" specific class (either directly or a subclass). `as` and `as?` are "cast" and "safe cast" respectively, instead – user2340612 Dec 03 '19 at 14:21

2 Answers2

1

Yes, @khelwood is right, it should be:

public abstract Class<? extends BaseViewModel> getViewModelClass();

and then I can use:

@Override
public Class<NetworkViewModel> getViewModelClass() {
    return NetworkViewModel.class;
}

Thank you.

Michalsx
  • 3,446
  • 5
  • 33
  • 46
1

Note that in Kotlin you shouldn't be using as here either; your superclass should declare

abstract fun selectViewModel(): Class<out BaseViewModel>

where Class<out BaseViewModel> is the equivalent to Java Class<? extends BaseViewModel>, and then

override fun selectViewModel() = NetworkViewModel::class.java

will work.

In case you do need to cast, the equivalent to x as SomeType is (SomeType) x; but in this case you'll probably need a double cast

return (Class<BaseViewModel>) (Class<?>) NetworkViewModel.class;

because Java compiler notices Class<NetworkViewModel> and Class<BaseViewModel> are incompatible.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487