我做了这个函数来转换Any的数组列表?到Double的数组列表,或为null。我错过了任何可能的事吗?
fun toArrayListDoubleOrNull(arg: ArrayList<Any?>): ArrayList<Double>? {
if (arg.isNullOrEmpty() || arg.contains(null)) {
return null;
}
arg.forEach { i: Any? ->
if (i.toString().trim().toDoubleOrNull() == null) {
return null;
}
};
val ret = ArrayList<Double>();
arg.forEach { i: Any? -> ret.add(i.toString().trim().toDouble()); };
return ret;
}
我相信你的原始用例可以用更好的方式解决,所以也许你想分享为什么首先需要这个功能。在此之前,您可以执行以下操作:
fun List<Any?>.toDoubles(): List<Double>? =
takeIf { isNotEmpty() && none { e -> e == null || e !is Double } }?.map { it as Double }
在行动:
val allDouble = listOf<Any>(1.0, 2.0, 3.0)
val stuff = listOf("", 1, 2.0, 3.0)
val doublesAndNull = listOf<Any?>(1.0, null, 2.0)
println(allDouble.toDoubles()) //[1.0, 2.0, 3.0]
println(stuff.toDoubles()) //null
println(doublesAndNull.toDoubles()) //null
根据您的要求,这是一种更“惯用”的方法:
fun toArrayListDoubleOrNull(input: ArrayList<Any?>): List<Double>? {
val result = input
.filter { it is Double }
.map { it as Double }
return if(result.size == input.size) {
result
} else {
null
}
}
免责声明它现在返回一个List而不是一个ArrayList
为了测试它,我写了以下测试:
class ArrayListToDouble {
@Test
fun `toArrayListDoubleOrNull with null values`() {
val input: ArrayList<Any?> = arrayListOf(12.0, 13.0, null)
val doubleArrayList = stackoverflow.toArrayListDoubleOrNull(input)
assertTrue(doubleArrayList == null)
}
@Test
fun `toArrayListDoubleOrNull without null values`() {
val input: ArrayList<Any?> = arrayListOf(12.0, 13.0)
val output: List<Double> = stackoverflow.toArrayListDoubleOrNull(input)!!
assertTrue(output == arrayListOf(12.0, 13.0))
}
}
更惯用的是使用扩展功能:
fun List<Any?>.toDoubleListOrNull(): List<Double>? {
val result = this
.filter { it is Double }
.map { it as Double }
return if(result.size == this.size) {
result
} else {
null
}
}
你可以这样称呼它:
val input = arrayListOf(12.0, 15.2)
val output = input.toDoubleListOrNull()