woong's

Android Kotlin When 사용하기 본문

Develop/Android

Android Kotlin When 사용하기

dlsdnd345 2017. 12. 10. 18:05
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android Kotlin When 사용하기


코틀린의 when 이라는 예약어를 통해서 다중 if 문 , switch 을 대체 할수 있습니다.

사용방법은 간단하고 명확합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    /**
     * 프래그먼트 변경
     */
    private fun replaceFragments(position: Int) {
 
        supportFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> {
                    replace(R.id.frameFragment, followFragment)
                }
                1 -> {
                    replace(R.id.frameFragment, unFollowFragment)
                }
                2 -> {
                    replace(R.id.frameFragment, recentUnFollowFragment)
                }
                3 -> {
                    replace(R.id.frameFragment, fanFragment)
                }
                else -> {
                    replace(R.id.frameFragment, UnFollowFragment())
                }
            }
        }.commitAllowingStateLoss()
    }
cs


제가 사용한 when에 대한 예제 입니다. when () 괄호 안에 분기에 해당하는 값을 넣어주고

value -> {} 를 통해서 다중 분기가 가능합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    /**
     * 프래그먼트 변경
     */
    private fun replaceFragments(position: Int) {
 
        supportFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> replace(R.id.frameFragment, followFragment)
                1 -> replace(R.id.frameFragment, unFollowFragment)
                2 -> replace(R.id.frameFragment, recentUnFollowFragment)
                3 -> replace(R.id.frameFragment, fanFragment)
                else -> replace(R.id.frameFragment, UnFollowFragment())
            }
        }.commitAllowingStateLoss()
    }
cs


{} 안의 내용이 한줄인경우, 위와같이 코드를 간결하게도 나타낼수 있습니다.

Comments