如何在 switch 语句中分配变量?

how to assign variable inside switch statement?

我刚开始使用 Kotlin。我想在 switch 语句中分配一个变量。这是代码:

when (position)
{
   1 -> fragmentManager.beginTransaction().hide(active).show(homeFragment).commit()
        active = homeFragment
}

在上面的代码中,在 active = homeFragment 行中,出现以下错误:Assignments are not expressions, and only expressions are allowed in this context

如何解决这个问题?无法在 kotlin 中的开关盒内分配变量吗?

你可以这样赋值

when (position)
{
    1 -> {

        fragmentManager.beginTransaction().hide(active).show(homeFragment).commit()
        active = homeFragment
    }
}

试试这个方法

when (position)
{
   1 -> {
         supportFragmentManager.beginTransaction().hide(active).show(homeFragment).commit()
         active = homeFragment
        }
}

还有

您应该使用 supportFragmentManager 而不是 fragmentManager

Because fragmentManager is deprecated

使用

supportFragmentManager.beginTransaction().hide(active).show(homeFragment).commit()

而不是

fragmentManager.beginTransaction().hide(active).show(homeFragment).commit()

如果您的 'when' 句子将有多个具有相同结构的选项,您可以将其设为 return 所选片段的值,例如:

active = when(option) {
             1 —> homeFragment.also {
                      fragmentManager.beginTransaction().hide(active).show(it).commit()
                  }
         }