개인 자료란 (JE)

  서버 커뮤니티

Profile muqhc 대표칭호 없음
Profile

커뮤니티 소통 개발하기 잡담

활성 패턴 in Kotlin

2022.05.12 조회 수 1120 추천 수 0

F#에 있는 활성 패턴을 코틀린에 구현(?) 해보았습니다.


다음의 Color 클레스가 있다고 합시다.


// Just a 'Color' class
class Color(val hex: Int)


이때, 다음과 같이 RGB 활성 패턴을 만들 수 있습니다.


val RGB = // create Active Pattern for 'Color'
    ActivePattern<Color, (red:Int,green:Int,blue:Int) -> Any> {
        val blue = input.hex % 256
        val green = (input.hex shr 8) % 256
        val red = (input.hex shr 16) % 256
        export(red,green,blue)
    }


그리고 다음과 같이 Color를 RGB 활성 패턴에 매칭 할 수 있습니다.


val obj = Color(0xFF00FF)

// do pattern match
match(obj) {
    // use Active Pattern
    case(RGB) { red, green, blue ->
        println("Color(red=$red,green=$green,blue=$blue)")
    }
    // when match nothing
    else_ { throw Exception("Not a Color") }
}


쓸일이 있을지는 모르겠으나,

자세한건 -> Github(https://github.com/muqhc/kotching) 를 참고 할 수 있습니다.




Warning
댓글이 없습니다.

새로운 댓글을 등록해 주세요!

뉴스 및 창작물
/files/thumbnails/218/767/003/262x150.crop.jpg?20240412130213

레드스톤

우리의 꿈 - 원피스 오프닝

노트블럭전문가

2024-04-12

0

/files/thumbnails/505/766/003/262x150.crop.jpg?20240411122306

레드스톤

기동전사 건담 수성의 마녀 | 노트블럭 커버 1

노트블럭전문가

2024-04-11

1

/files/thumbnails/932/765/003/262x150.crop.jpg?20240410124459

레드스톤

마인크래프트 노트블록으로 만든 『 밤양갱 (Bam Yang Gang) 』

노트블럭전문가

2024-04-10

0

/files/thumbnails/403/765/003/262x150.crop.jpg?20240409190538

레드스톤

마인크래프트 노트블록으로 만든 『 밤양갱 (Bam Yang Gang) 』

Sonttukk

2024-04-09

4

/files/thumbnails/161/758/003/262x150.crop.jpg?20240331105743

레드스톤

라마 침 분수대

GlassesFilm

2024-03-31

0