Kotlin 中的一个大问题是不能像 Apple 中的 swift 那样动态转换。我能怎么做?

nac*_*111 1 android kotlin firebase-realtime-database

我有一个 firebase 实时数据库,具有以下简单的方案:

  • 行政
    • 价格1:5

如果我在 kotlin 中获取数据库:

val result = it.value as MutableMap<String, Any>
Run Code Online (Sandbox Code Playgroud)

当我尝试获取价格1时

var price1 = result["price1"] as Long
price1 = price1 + 1
Run Code Online (Sandbox Code Playgroud)

(PRICE1 可以是 Double 或 Int)问题是,如果价格 1 是 5.5,显然应用程序会被杀死,但如果价格 1 是 5,则完美运行。

迅速地,我每次都输入 Double 并且它永远不会出现问题

我发现必须检查它是双精度数还是不带逗号的整数才能进行求和有点愚蠢

// im doing this at the moment
var price1 = result["price1"].toString()
if (price1.contains(".")){
     println(price1.toDouble() + 1)
}else{
     println(price1.toInt() + 1)
}
Run Code Online (Sandbox Code Playgroud)

还有其他简单的方法吗?感谢大家

luk*_*s.j 5

Kotlin 对类型非常严格,这对于类型安全非常重要。

\n

在您的情况下,您会从result中获得Any类型的值。它可以是任何东西,而不仅仅是IntDouble知道它只能是 Int 或 Double,但编译器不知道。许多语言允许隐式的东西,例如类型转换(int 到 double)、类型加宽(int 到 long)等。但这些通常是令人讨厌的错误的来源。另请参阅此讨论有人觉得 Kotlin\xe2\x80\x99s 类型转换令人厌恶吗?

\n

关于您的代码:要测试您使用的类型的值

\n

以下是如何加一的示例:

\n
fun increment(value: Any): Any {\n  return when (value) {\n    is Double -> value + 1.0\n    is Int    -> value + 1\n    else      -> throw Exception("Value is neither a Double nor an Int")\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

你会这样使用它:

\n
val result: MutableMap<String, Any> = mutableMapOf(\n  "price1" to 3,\n  "price2" to 3.45\n)\n\nvar price1: Any = result["price1"]!!   // 3\nprice1 = increment(price1)\nprintln(price1)   // 4\nprice1 = increment(price1)\nprintln(price1)   // 5\n\nvar price2: Any = result["price2"]!!   // 3.45\nprice2 = increment(price2)\nprintln(price2)   // 4.45\nprice2 = increment(price2)\nprintln(price2)   // 5.45\n
Run Code Online (Sandbox Code Playgroud)\n

我不知道 Kotlin 是否会有联合类型。那么这样的声明是可能的:

\n
val result: MutableMap<String, [Int|Double]>   // invalid code\n
Run Code Online (Sandbox Code Playgroud)\n