在Kotlin中扩展时,类需要的类型实参 [英] Type argument required for a class while extending in kotlin

查看:60
本文介绍了在Kotlin中扩展时,类需要的类型实参的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题很简单, 在Java中,如果我有这样的基类:

So my problem is simple, In java if i have a base class like this:

BaseViewModel.Java

BaseViewModel.Java

public abstract class BaseViewModel<N> extends ViewModel {

我可以将此类扩展到其他类,而无需定义通用参数N,如下所示:

I can extend this class to other classes without defining the generic argument N, like this:

public class BaseFragment<V extends BaseViewModel> { //this is fine

但是kotlin用这种方法要求通用定义时会出错.

but kotlin throws an error with this approach asking for the generic definition.

class BaseFragment<V: BaseViewModel>: Fragment() {// one type argument expected

如何避免这种情况?

推荐答案

与Java一样,Kotlin不允许使用原始类型.因此,您必须为V : BaseViewModel指定某种类型:

Kotlin doesn't allow to use raw types as Java does. Thus, you have to specify some type for your V : BaseViewModel:

class BaseFragment<V: BaseViewModel<Any>>: Fragment() {

这与您的Java代码等效,因为V extends BaseViewModel基本上表示V extends BaseViewModel<Object>

It is equivalent for your Java code cause V extends BaseViewModel basically means V extends BaseViewModel<Object>

这篇关于在Kotlin中扩展时,类需要的类型实参的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆