如果null则无效

Has*_*sef 1 android kotlin

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

我得到错误的函数是:

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
                    )
                }
        )
Run Code Online (Sandbox Code Playgroud)

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)
                }
    }
}
Run Code Online (Sandbox Code Playgroud)

ice*_*000 5

fun getLocation(context: Context, callback: (Location) -> Unit)中,参数Locationcallback是NOTNULL,所以它永远不能为null,这就是为什么location?.let会导致一个警告-这是从来没有空,因此它不可能进入?: run表达式的一部分.

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

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)
                }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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)
}
Run Code Online (Sandbox Code Playgroud)