ラベル付き戻り値

Kotlin

次のコードの「return@setOnClickListener」は「ラベル付き戻り値」というもので、ただのreturnとは異なります。

ただのreturnだと関数全体から完全に戻ってしまいますが、btnLogin.setOnClickListenerからだけ抜けたい場合はこのようにラベル付き戻り値を使います

class LoginActivity : AppCompatActivity() {

    private lateinit var prefs: PrefsManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_login)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.login)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val etName = findViewById<EditText>(R.id.etName)
        val etPass = findViewById<EditText>(R.id.etPass)
        val btnLogin = findViewById<Button>(R.id.btnLogin)
        prefs = PrefsManager(this)

        btnLogin.setOnClickListener {
            val name = etName.text.toString().trim()
            val pass = etPass.text.toString().trim()

            if (name.isEmpty() || pass.isEmpty()) {
                Toast.makeText(this, "ユーザー名もしくはパスワードが入力されていません", Toast.LENGTH_LONG).show()
                return@setOnClickListener  <---- この部分
            }
        }

    }
}
BACK