Break inside a if condition (in a when)

Hi, how can I get out of an if condition ? My condition is in a when I precise.

Or maybe can you tell me why afterTextChanged is not working when it’s the first time (maybe because I need text ?)

if(textViewLabel.text == "Quantité"){
    input.onFocusChangeListener = View.OnFocusChangeListener { view, hasFocus ->
        if (!hasFocus && input.text.toString() != "") {
            val quantite = Integer.parseInt(input.text.toString())
            input.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
                override fun afterTextChanged(e: Editable?) {
                    if (e.toString() != "") {
                        first = false
                        println("ancienne quantite : $quantite")
                        val newQuantite = Integer.parseInt(e.toString())
                        println("nouvelle quantite : $newQuantite")
                        val valDiff = valDiff(quantite, newQuantite)
                        println("differ.  quantite : $valDiff")
                        val newPrice = prixDiff(valDiff, 1.0f)
                        total = totalModif(newPrice, total)
//do this if it's not the first time
                        textViewLabel.visibility = View.VISIBLE
                        Toast.makeText(baseContext, total.toString(), Toast.LENGTH_SHORT).show()
                    } else {
                        textViewLabel.visibility = View.GONE
                    }
                }
            }) // do this the first time
                total = calc(quantite, 1.0f, total)
                Toast.makeText(baseContext, total.toString(), Toast.LENGTH_SHORT).show()
        }
    }
}

You can return to labels. Although I’d recommend refactoring to make the code a little cleaner.

Personally, in a code review I’d ask about these points:

  • The function is more than 20 lines: What’s the justification?
  • This function appears to do more than one thing: Have you considered splitting up the tasks?
  • toString() != "" is used a couple times and its purpose isn’t as clear (this is confirmed by having to add comments): Have you considered using String.isNotEmpty() and String.isEmpty() or better yet, naming the boolean or function?
  • Those comments are a good sign the control flow is not clear enough on its own: Have you considered wrapping your conditions in private named functions?
  • The outer if, the anonymous TextWatcher, and the override of afterTextChanged create a lot of nested code with low cohesion: Have you considered moving them somewhere else?