Abner Escócio
Abner Escócio

Reputation: 2785

Code works outside of lambda expression, but not from within

I have the follow code:

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
}

But, when I apply it as follows:

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
}

I'm facing these two errors:

error 1.

'return' is not allowed here

error 2.

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException

I know what each error means, but

My question is: why does my code work outside of the lambda expression and does not work when inside? And how do I solve this?

UPDATED

The @Rene Ferrari's solution solve the error 1. Thanks a lot @Rene Ferrari

Upvotes: 1

Views: 75

Answers (1)

Rene Ferrari
Rene Ferrari

Reputation: 4206

Based of mTak answer my solution is the following:

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
}

You can basically define a label to which you want to return. This label can be named anything except keywords ofcourse. In this example I named it returnHere

Upvotes: 1

Related Questions