Scala 에서 Enumeration 사용하기
http://alvinalexander.com/scala/how-to-use-scala-enums-enumeration-examples 참조
문제 ) 스칼라에서 enumeration 을 사용하고 싶습니다.(상수로서 사용되는 문자열 )
해결책 1 ) Enumeration 클래스를 사용해서 열거형 만들기
scala.Enumeration 클래스를 확장하세요.
package com.acme.app {
object Margin extends Enumeration {
type Margin = Value
val TOP, BOTTOM, LEFT, RIGHT = Value
}
}
그리고 이것을 import 로 가져가서 사용하심 됩니다
object Main extends App {
import com.acme.app.Margin._
// use an enumeration value in a test
var currentMargin = TOP
// later in the code ...
if (currentMargin == TOP) println("working on Top")
// print all the enumeration values
import com.acme.app.Margin
Margin.values foreach println
}해결책 2 ) traits / case 를 사용해서 열거형 만들기
// a "heavier" approach
package com.acme.app {
trait Margin
case object TOP extends Margin
case object RIGHT extends Margin
case object BOTTOM extends Margin
case object LEFT extends Margin
}
Enumeration 의 문제점 - 1
메소드 오버로딩에 문제가 생긴다. 아래를 보자.
/**
* Created by brad on 2016-09-30.
*/
import scala.collection._
import scala.util.parsing.json._
object Colours extends Enumeration {
val Red, Amber, Green = Value
}
object WeekDays extends Enumeration {
val Mon,Tue,Wed,Thu,Fri = Value
}
object Functions {
def f(x: Colours.Value) = println("That's a colour")
def f(x: WeekDays.Value) = println("That's a weekday")
}
object test {
import Colours._
def main(arg : Array[String]): Unit ={
Functions.f(Red)
}
}Error:(19, 7) double definition:
method f:(x: WeekDays.Value)Unit and
method f:(x: Colours.Value)Unit at line 18
have same type after erasure: (x: Enumeration#Value)Unit
def f(x: WeekDays.Value) = println("That's a weekday")
이 경우에 에러가 발생한다. Red 라고 명시했지만 구분 할 수 없다.
'Scala' 카테고리의 다른 글
| 스칼라 강좌 (18) -trait (1) | 2016.08.06 |
|---|---|
| 스칼라 강좌 (17) - case class (0) | 2016.08.06 |
| 스칼라 강좌 (15) - Getter / Setter (0) | 2016.07.31 |
| 스칼라 강좌 (14) - 함수 와 메소드 (0) | 2016.07.23 |
| 스칼라 강좌 (13) - 클래스와 객체 (0) | 2016.07.16 |