2017-07-18 64 views
5

我試圖延長,在Java中,一個科特林委託類,並收到以下錯誤:我可以使用Java擴展Kotlin授權類嗎?

Cannot inherit from final 'Derived'

見下面的代碼。

我想要做的是裝飾一個類的方法。

任何想法爲什麼Kotlin將Derived定義爲最終?有沒有辦法讓Derived不是最終的,所以我可以繼承它?

的Java:

new Derived(new BaseImpl(10)) { // Getting the error on this line: `Cannot inherit from final 'Derived'` 
}; 

科特林:從這裏

interface Base { 
    fun print() 
} 

class BaseImpl(val x: Int) : Base { 
    override fun print() { print(x) } 
} 

class Derived(b: Base) : Base by b 

*示例:https://kotlinlang.org/docs/reference/delegation.html

回答

9

Kotlin classes are final in by default。將類標記爲open(從科特林或從Java是否)擴展它:

open class Derived(b: Base) : Base by b 

的事實,這是一個委託類應該對Java的互操作沒有影響(雖然我還沒有嘗試過)。