代码之家  ›  专栏  ›  技术社区  ›  Abner Escócio

代码在lambda表达式之外工作,但不是从内部工作

  •  1
  • Abner Escócio  · 技术社区  · 6 年前

    我有以下代码:

    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。

    此处不允许使用“return”

    错误2。

    调用需要用户可能拒绝的权限:代码应 显式检查权限是否可用(使用 或显式处理潜在的SecurityException

    我知道每个错误的含义,但是

    我的问题是: 为什么我的代码在lambda表达式之外工作,而在lambda表达式内部不工作?我怎么解决这个问题?

    更新

    这个 @Rene Ferrari's solution 解决 错误1 . 谢谢 @Rene Ferrari

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rene Ferrari    6 年前

    基于mtak answer,我的解决方案如下:

    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