2017-08-08 83 views
0

我使用的是從https://github.com/nekocode/android-parcelable-intellij-plugin-kotlinParcelable派生類在科特林

我這個定義

class ChessClock : TextView { 
    lateinit var player:String 
    constructor(context: Context) : super(context) 
    constructor(context:Context, p:String, angle:Float) : this(context) { 
     player = p 
     rotation = angle 
    } 
    <snip> 
} 

和定義改爲

class ChessClock() : TextView, Parcelable { 
    lateinit var player:String 
    constructor(context: Context) : super(context) 
    constructor(context:Context, p:String, angle:Float) : this(context){ 
     player = p 
     rotation = angle 
    } 
    <snip -- various stuff added here> 
} 

試圖在類的Android Parcelable插件突出顯示了兩個語法錯誤。

在行

class ChessClock() : TextView, Parcelable 

TextView有下劃線與評論「這種類型有一個構造函數,並且必須在這裏初始化。」

在行

constructor(context: Context) : super(context) 

super有下劃線與評論「主構造函數調用的預期。」

我只用了kotlin幾個星期,我不明白這裏發生了什麼。首先,我知道(或至少我認爲我知道)科特林沒有實現多重繼承,所以我不明白是什麼

類ChessClock():TextView的,Parcelable

手段。這真的是合法的kotlin嗎?如何在kotlin中創建派生類Parcelable?

回答

2
  1. TextView的一類,因此你的主構造應該 調用它的構造函數之一
  2. ,則應該從其他構造

實例調用你的主構造:

class ChessClock(context: Context) : TextView(context), Parcelable 

//in this case you don't need other constructors but in-case you do, this is how you should write it: 
constructor(context: Context, dummy: Int): this(context) 
+0

完美。謝謝。 – saulspatz

+0

糟糕。我說得太快了。現在我看到編譯器抱怨聲明'constructor(parcel:Parcel):this()'。該聲明應該如何改變? – saulspatz

+0

我打算讓這個問題成爲一個新問題。 – saulspatz

0

你也可以將生成的代碼從ChessClock()更改爲ChessClock

+0

但這不會幫助你解決'構造函數(parcel:Parcel)'問題,請參閱我的[回答你的其他問題](https://stackoverflow.com/questions/45578982/constructor-taking-parcelable-constructor- in-kotlin-derived-class/45579620#45579620)...但簡短的答案是不要試圖讓你的UI可以被分類,如果可以的話,將UI與支持數據分開。 – Les