简体   繁体   中英

What is Java synonym for Kotlin "as"?

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?

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.

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> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM