2016-07-31 259 views
1

我一直在閱讀有關properties在科特林,包括自定義getter和setter方法將參數傳遞給定製吸氣。在科特林

不過,我想知道是否有可能創建一個額外的參數定製吸氣。

例如,請考慮以下方法在Java中:

public String getDisplayedValue(Context context) { 
    if (PrefUtils.useImperialUnits(context)) { 
     // return stuff 
    } else { 
     // return other stuff 
    } 
} 

注意,在PrefUtils靜態方法必須具有Context作爲參數,因此刪除這是不是一種選擇。

我想將它寫像這樣在科特林:

val displayedValue: String 
    get(context: Context) { 
     return if (PrefUtils.useImperialUnits(context)) { 
      // stuff 
     } else { 
      // other stuff 
     } 
    } 

但我的IDE亮點所有這一切都爲紅色。

我知道我可以在我的班級中創建一個函數來獲取顯示的值,但這意味着我將不得不在Kotlin中使用.getDisplayedValue(Context),而不能像在.displayedValue中那樣按名稱引用屬性。

有沒有辦法像這樣創建一個自定義getter?

編輯:如果不是,最好是爲此編寫一個函數,或者將Context傳遞給類構造函數的參數?

回答

3

據我所知,屬性getter不能有參數。改寫一個函數。

+0

難道是不好的做法,通過'Context'到類的構造函數使用自定義的getter的參數? –

+0

這不是最簡單的方法,但如果你需要一個屬性的語法,那麼做 – voddan

1

比如,你可以這樣做:

val displayedValue: String by lazy { 
    val newString = context.getString(R.string.someString) 
    newString 
}