我有以下代码:
override fun onCreate(savedInstanceState: Bundle?) {
...
fab_action.setOnClickListener(actionSetMyLocationEnable) //passing my lambda
}
private val actionSetMyLocationEnable: (View) -> Unit = { it as FloatingActionButton
it.isSelected = !it.isSelected
setMyLocationEnable(it.isSelected) //this call work fine
}
private fun setMyLocationEnable(enable: Boolean) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return //and this return work nice too
}
mMap.isMyLocationEnabled = enable
}
但是,当我按以下方式应用它时:
private val actionSetMyLocationEnable: (View) -> Unit = { it as FloatingActionButton
it.isSelected = !it.isSelected
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return //error 1
}
mMap.isMyLocationEnabled = it.isSelected //error 2
}
我遇到了两个错误:
错误1。
此处不允许“返回”
错误2。
呼叫需要许可,但可能会被用户拒绝:代码应 明确检查权限是否可用(带有 checkPermission)或显式处理潜在的SecurityException
我知道每个错误的含义,但是
我的问题是:为什么我的代码在lambda表达式之外无法工作,而在lambda表达式之外却不能工作?而我该如何解决呢?
已更新
@Rene Ferrari's solution解决了错误1 。非常感谢@Rene Ferrari
答案 0 :(得分:1)
基于mTak的答案,我的解决方法是:
private val actionSetMyLocationEnable: (View) -> Unit = returnHere@{ it as FloatingActionButton
it.isSelected = !it.isSelected
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return@returnHere //error 1
}
mMap.isMyLocationEnabled = it.isSelected //error 2
}
您基本上可以定义要返回的标签。该标签可以命名为课程关键字以外的任何名称。在此示例中,我将其命名为returnHere