在 Kotlin 中,資料類的屬性可以有多種型別嗎?例如:
val CurrentValue: Double?|String 還是 val CurrentValue: String|Array?
我在檔案中找不到它。
uj5u.com熱心網友回復:
聯合型別在 Kotlin 中不是一個東西。
您可以使用 asealed class代替。
sealed class CurrentValue<T>(val value: T) {
class TextualValue(value: String) : CurrentValue(value)
class NumericValue(value: Double) : CurrentValue(value)
}
然后您可以使用詳盡的when運算式(類似于switch其他語言)以便以型別安全的方式訪問值:
fun doSomething(value: CurrentValue<*>) {
when(value) {
is TextualValue -> value.value // is recognised as a String
is NumericValue -> value.value // is recognised as a Double
}
}
如果創建型別對您來說太多了,那么您可以執行一個when陳述句并根據它的型別處理一個引數,并可能對其進行規范化:
fun parseValue(value: Any?): Double? = when(value){
is Double -> value
is String -> value.toDoubleOrNull()
is Int -> value.toDouble()
else -> null
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432436.html
標籤:科特林
