如果null则无效

时间:2018-03-30 11:40:52

标签: android kotlin

如果location为null,我想执行一个msg;如果它不为null,我想执行另一个msg,所以我尝试使用elvis-operator作为a?.let{} ?: run{}语句,但是run部分无法访问,它告诉我它不是必需的也不是不可空的!

我收到错误的函数是:

getLocation(
           context,
                { location ->
                    location?.let {
                        msg = ("As of: ${Date(it.time)}, " +
                                "I am at: http://maps.google.com/?q=@" +
                                "${it.latitude}, ${it.longitude}, " +
                                "my speed is: ${it.speed}")
                    } ?: run { . // Getting error here
                        msg = "Sorry, it looks GPS is off, no location found\""
                    }

                    sendSMS(
                            context,
                            address,
                            msg,
                            subId
                    )
                }
        )

Th getLocation函数是:

object UtilLocation {
    private lateinit var l : Location

    @SuppressLint("MissingPermission")
    fun getLocation(context: Context, callback: (Location) -> Unit) {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

        fusedLocationClient.lastLocation
                .addOnSuccessListener { location : Location? ->
                    this.l = location!!
                    callback.invoke(this.l)
                }
    }
}

1 个答案:

答案 0 :(得分:5)

fun getLocation(context: Context, callback: (Location) -> Unit)中,Location的参数callback为NotNull,因此它永远不会为空,这就是location?.let导致警告的原因 - 它&# 39; s永远不会为空,因此无法输入表达式的?: run部分。

AFAIK你想要这个代码(callback的参数是Nullable,删除不必要的NotNull断言,添加null check而不是断言):

object UtilLocation {
    private lateinit var l : Location

    @SuppressLint("MissingPermission")
    fun getLocation(context: Context, callback: (Location?) -> Unit) {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
        fusedLocationClient.lastLocation
                .addOnSuccessListener { location : Location? ->
                    if (location != null) this.l = location
                    callback.invoke(this.l)
                }
    }
}

现在这段代码工作了。我做了一点重构让它看起来更漂亮

getLocation(context) { location ->
    msg = location?.let {
        "As of: ${Date(it.time)}, " +
                "I am at: http://maps.google.com/?q=@" +
                "${it.latitude}, ${it.longitude}, " +
                "my speed is: ${it.speed}"
    } ?: run {
        "Sorry, it looks GPS is off, no location found\""
    }

    sendSMS(context, address, msg, subId)
}