Flutter method以kotlin方式调用非nil检查



我试图使用kotlin制作一个MethodCall类型判断函数,但它为我返回类型不匹配,我应该如何修复它?

import java.util.Objects
import io.flutter.plugin.common.MethodCall
class Utils private constructor() {
companion object {
fun getDoubleArgument(call: MethodCall, argument: String?): Double {
return try {
if (call.argument<Any>(argument) is Double) {
Objects.requireNonNull(call.argument<Double>(argument))!!  // The call.argument return Double? type, but when I add !! assert, it report Unnecessary non-null assertion (!!).
} else if (call.argument<Any>(argument) is Long) {
val l = Objects.requireNonNull(call.argument<Long>(argument))
l!!.toDouble()
} else if ...
}

我不使用Flutter,所以请原谅任何错误。

在Kotlin中你不需要Objects.requireNonNull(),因为!!已经做了与requireNonNull()完全相同的事情,除了它抛出KotlinNullPointerException而不是NullPointerException。它不能工作的原因是Kotlin不知道Java方法保证返回一个非空值。

class Utils private constructor() {
companion object {
fun getDoubleArgument(call: MethodCall, argument: String?): Double {
return try {
if (call.argument<Any>(argument) is Double) {
call.argument<Double>(argument)!!
} else if (call.argument<Any>(argument) is Long) {
call.argument<Long>(argument)!!.toDouble()
} else if ...
}

最好一次获取实参并使用该值。然后,您可以依靠Kotlin智能强制转换来简化代码:

class Utils private constructor() {
companion object {
fun getDoubleArgument(call: MethodCall, argument: String?): Double {
val arg = call.argument<Any>(argument)
return try {
if (arg is Double) {
arg
} else if (arg is Long) {
arg.toDouble()
} // ...
else if (arg == null) {
0.0
} else {
error("unsupported argument type")
}
}

您可以使用when语句而不是else if链,以使其更易于阅读:

class Utils private constructor() {
companion object {
fun getDoubleArgument(call: MethodCall, argument: String?): Double {
val arg = call.argument<Any>(argument)
return try {
when (arg) {
is Double -> arg
is Long -> arg.toDouble()
// ...
null -> 0.0
else -> error("unsupported argument type")
}
}
}

最新更新