2017-06-17 54 views
4

我有一個簡單的輔助函數從SharedPreferences得到的值是這樣的:Kotlin - 不能使用'T'作爲實體類型參數。使用一個類,而不是

operator inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? { 
    return when (T::class) { 
     String::class -> getString(key, defaultValue as? String) as T? 
     Int::class -> getInt(key, defaultValue as? Int ?: -1) as T? 
     Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T? 
     Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T? 
     Long::class -> getLong(key, defaultValue as? Long ?: -1) as T? 
     else -> throw UnsupportedOperationException("Not yet implemented") 
    } 
} 

我已經用具體化類型參數有切換是類類型,因爲它是一個運營商的功能,我應該是能夠用方括號語法來調用象下面這樣:

val name: String? = prefs[Constants.PREF_NAME] 

但是,我每次調用它,UnsupportedOperationException異常被拋出指示功能是不是能夠得到類類型。

當我連接調試和評估T::class,這是給我一個錯誤"Cannot use 'T' as reified type parameter. Use a class instead."

這有什麼錯我的功能?我無法理解這個錯誤。誰能幫忙?

編輯:整個班級是herethis is where我得到的錯誤。

更新:這似乎是Kotlin編譯器問題。 跟蹤https://youtrack.jetbrains.com/issue/KT-17748https://youtrack.jetbrains.com/issue/KT-17748更新。

+0

我無法重現你的錯誤。我可以注意到的一件事是你沒有返回'when'的結果,所以它總是會返回null。 –

+0

@JornVernee你能看到這個:https://gist.github.com/krupalshah/782c42c70f2c58004c9bbda6291315e6我需要你的幫助。 –

+0

如果我無法重現錯誤,我無法幫助您。 –

回答

2

問題很好奇,但似乎Int::class是不一樣的Int?::class(這是一種非法的表達方式)。

當你添加一行:

println(T::class) 

get方法,並調用val age: Int? = prefs["AGE", 23],你會看到,它打印java.lang.Integer

好像Int?被翻譯成java.lang.Integer

一種可能(但恕我直言一種哈克的)解決方案是使用Java類的情況下,引用的時候:

operator inline fun <reified T : Any> get(key: String, defaultValue: T? = null): T? { 
    return when (T::class) { 
     String::class -> getString(key, defaultValue as? String) as T? 
     java.lang.Integer::class -> getInt(key, defaultValue as? Int ?: -1) as T? 
     java.lang.Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T? 
     java.lang.Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T? 
     java.lang.Long::class -> getLong(key, defaultValue as? Long ?: -1) as T? 
     else -> throw UnsupportedOperationException("Not yet implemented") 
    } 
} 
+0

謝謝。你是對的。第一種解決方案現在也運行良好。我們發現了Kotlin編譯器中的新bug嗎? –

+1

@KrupalShah不是一個錯誤,也許是一個缺點;它比較'java.lang.Integer :: class'到'Int :: class'時沒有特別的處理。 –

+0

嗯..好的。你的第二個解決方案是好的,但唯一的問題是我應該能夠作爲默認值傳遞null,即使我想要字符串。那一次它不會工作。 –

相關問題