nac*_*111 1 android kotlin firebase-realtime-database
我有一个 firebase 实时数据库,具有以下简单的方案:
如果我在 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)
还有其他简单的方法吗?感谢大家
Kotlin 对类型非常严格,这对于类型安全非常重要。
\n在您的情况下,您会从result中获得Any类型的值。它可以是任何东西,而不仅仅是Int或Double。您知道它只能是 Int 或 Double,但编译器不知道。许多语言允许隐式的东西,例如类型转换(int 到 double)、类型加宽(int 到 long)等。但这些通常是令人讨厌的错误的来源。另请参阅此讨论有人觉得 Kotlin\xe2\x80\x99s 类型转换令人厌恶吗?
\n关于您的代码:要测试您使用的类型的值是。
\n以下是如何加一的示例:
\nfun 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}\nRun Code Online (Sandbox Code Playgroud)\n你会这样使用它:
\nval 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\nRun Code Online (Sandbox Code Playgroud)\n我不知道 Kotlin 是否会有联合类型。那么这样的声明是可能的:
\nval result: MutableMap<String, [Int|Double]> // invalid code\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |