亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Kotlin:擴展動態給定的超類型

Kotlin:擴展動態給定的超類型

一只甜甜圈 2022-06-15 17:12:38
假設我有課程:class A : SuperType() {}class B : SuperType() {}class C : B() {}假設我不想C再擴展B():我希望它擴展A(),但現在我想A擴展B()。如何在編譯時A擴展B()(或任何子級SuperType())而不是僅擴展SuperType()?換句話說,我怎樣才能使類A聲明通用以接受任何孩子SuperType()?希望很清楚。我想做類似的事情:class B(whatever_it_receives_as_long_as_child_of_SuperType) : whatever_it_receives_as_long_as_child_of_SuperType()class C : A(B())    // B is subtype of SuperType so it's ok
查看完整描述

2 回答

?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

如何在編譯時生成 A 擴展 B()(或 SuperType() 的任何子級),而不僅僅是 SuperType()?

你不能。每個類只能擴展一個固定的超類。

我認為你能得到的最接近的是

class A(x: SuperType): SuperType by x

(請參閱文檔)但這需要SuperType是一個接口而不是一個類。


查看完整回答
反對 回復 2022-06-15
?
呼如林

TA貢獻1798條經驗 獲得超3個贊

您可以執行以下操作:


open class SuperType {}

open class A(val obj: SuperType) : B() {}

open class B : SuperType() {}

class C : A(B())

或使用泛型:


open class SuperType {}

open class A<T: SuperType>(val obj: T) : B() {}

open class B : SuperType() {}

class C : A<B>(B())


查看完整回答
反對 回復 2022-06-15
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號