Jayesh Babu
Jayesh Babu

Reputation: 1449

how to assign variable inside switch statement?

I just started using Kotlin. I want to assign a variable inside a switch statement. Here is the code:

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

In the above code , in the active = homeFragment line, i am getting the following error: Assignments are not expressions, and only expressions are allowed in this context

How to solve this issue? Is it not possible to assign variable inside switch case in kotlin?

Upvotes: 1

Views: 617

Answers (3)

Jesús Barrera
Jesús Barrera

Reputation: 459

If your 'when' sentence is going to have more than one options with the same structures you can make it return the value of the fragment selected, for instance:

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

Upvotes: 2

AskNilesh
AskNilesh

Reputation: 69681

Try this way

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

Also

You should use supportFragmentManager insteadof fragmentManager

Because fragmentManager is deprecated

Use

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

Instead of

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

Upvotes: 2

shafayat hossain
shafayat hossain

Reputation: 1129

You can assign in this way

when (position)
{
    1 -> {

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

Upvotes: 3

Related Questions