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

时间:2019-12-28 05:31:17

标签: android kotlin switch-statement variable-assignment

我刚开始使用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中的switch case中分配变量吗?

3 个答案:

答案 0 :(得分:4)

您可以通过这种方式分配

when (position)
{
    1 -> {

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

答案 1 :(得分:2)

尝试这种方式

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

您应该使用 supportFragmentManager 而不是 fragmentManager

  

因为fragmentManager已过时

使用

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

代替

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

答案 2 :(得分:2)

如果“ when”语句将具有多个具有相同结构的选项,则可以使其返回所选片段的值,例如:

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