Generics Kotlin泛型约束

Generics Kotlin泛型约束,generics,kotlin,Generics,Kotlin,我想创建一个可以接受有限泛型类型的类,这样我的类就只能接受某个特定类的子类。但是没有那么多演员。我的代码如下所示: open class SomeClass<V> where V : SomeType { private val vc: PS<SomeType> = PS.create() protected val z: ZQ<V> = vc.doSmt(-1).map { it as V } open fun onVc(v: V) {

我想创建一个可以接受有限泛型类型的类,这样我的类就只能接受某个特定类的子类。但是没有那么多演员。我的代码如下所示:

open class SomeClass<V> where V : SomeType { 
  private val vc: PS<SomeType> = PS.create()
  protected val z: ZQ<V> = vc.doSmt(-1).map { it as V }

  open fun onVc(v: V) {
    vc.on(v)
  } 
}
这是
SomeType
,它的超类和子类看起来像

interface SuperSomeType<S> {
  fun x(): Observable<S>
}

interface SomeType : SuperSomeType<EnumType1>
interface SomeOtherType : SuperSomeType<EnumType2> // just to show why I used SuperSomeType interface

class SubClassOfSomeType : SomeType {
  override fun x(): Observable<EnumType1> {
    return Observable.empty()
  }
}
interface SuperSomeType{
funx():可观察
}
接口SomeType:SuperSomeType
接口SomeOtherType:SuperSomeType//只是为了说明我为什么使用SuperSomeType接口
类SubassofSomeType:SomeType{
override fun x():可观察{
返回可观察的.empty()
}
}

谢谢你的建议,让它更清晰

你能举一个最小的、完整的、可验证的例子吗?代码中有很多未定义的类和函数。这让我很难尝试。你很可能只需要将你的类定义为
打开类SomeClass
。@marstran好的,我明天会添加完整的版本。是的,这比较短,但是
中使用了
,以防我想要上限超过1种类型。谢谢你的建议。通过使用
where
关键字,你可以有多个上限:
openclass SomeClass其中V:Sometype,V:SomeOtherType,V:SomeThirdType
示例仍然不完整。Rx类仍然未定义。该问题询问了对
SomeClass::onVc
的调用,但问题中没有任何调用。您能否给出一个最小、完整且可验证的示例?代码中有很多未定义的类和函数。这让我很难尝试。你很可能只需要将你的类定义为
打开类SomeClass
。@marstran好的,我明天会添加完整的版本。是的,这比较短,但是
中使用了
,以防我想要上限超过1种类型。谢谢你的建议。通过使用
where
关键字,你可以有多个上限:
openclass SomeClass其中V:Sometype,V:SomeOtherType,V:SomeThirdType
示例仍然不完整。Rx类仍然未定义。该问题询问了对
SomeClass::onVc
的调用,但问题中没有。
interface SuperSomeType<S> {
  fun x(): Observable<S>
}

interface SomeType : SuperSomeType<EnumType1>
interface SomeOtherType : SuperSomeType<EnumType2> // just to show why I used SuperSomeType interface

class SubClassOfSomeType : SomeType {
  override fun x(): Observable<EnumType1> {
    return Observable.empty()
  }
}