代码之家  ›  专栏  ›  技术社区  ›  Blazej SLEBODA

这是什么意思:return@OnNavigationItemSelectedListener

  •  0
  • Blazej SLEBODA  · 技术社区  · 6 年前

    “的意思是什么?”return@OnNavigationItemSelectedListener“在下面的代码中:

    class MainActivity : AppCompatActivity() {
    
        private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_home -> {
                    message.setText(R.string.title_home)
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_dashboard -> {
                    message.setText(R.string.title_dashboard)
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_notifications -> {
                    message.setText(R.string.title_notifications)
                    return@OnNavigationItemSelectedListener true
                }
            }
            false
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Sergey Glotov Nitesh Khosla    6 年前

    fun foo() {
        listOf(1, 2, 3, 4, 5).forEach lit@{
            if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
            print(it)
        }
        print(" done with explicit label")
    }
    

    返回表达式从最近的封闭函数返回,即foo(请注意,只有传递给内联函数的lambda表达式才支持这种非本地返回。)如果需要从lambda表达式返回,则必须标记它并限定返回:

    See more here