skip to Main Content

Let’s say I have a boolean completed that is out of the scope of the onClickListener that is attached to a Button.

What statement can I put inside this if block that will skip the entire code of this Button? (ignoring a messy solution like putting the whole code under the else block)

confirmBttn.setOnClickListener {
    if (completed) {
        *stop or skip the entire button code*
    }

    *code*
}

I am looking for an elegant solution to only stop that listener’s block; without stopping the whole program, or using an entire if/else block. Something like a function that simply terminates the particular call for this listener function.

2

Answers


  1. The ‘return’ keyword will stop the current scope at this point and prevents the code below to run. Other parts of your programm are not affected by this.

    confirmBttn.setOnClickListener {
        if (completed) return
    
        *code*
    }
    
    Login or Signup to reply.
  2. confirmBttn.setOnClickListener {
        if (completed) return@setOnClickListener
    
        *code*
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search