콘텐츠로 이동

2024 01 30

2024-01-30

Scala Enum vs Java Enum

참고: https://partnerjun.tistory.com/49

  • Java Enum
    • JVM이 지원하는 간편하게 생성 가능한 싱글톤
    • 프로그램 전역 호출 가능
    • Java의 Enum은 메서드나 생성자를 선언해 각각을 객체로써 기능하게 할 수 있음
      public enum Fruits {
          APPLE("red"), BANANA("yellow");
      
          private final string color;
      
          Fruits(String color) {
              this.color = color;
          }
      
          public String getColor() {
              return this.color;
          }
      }
      
  • Scala Enum

    • Java 처럼 기본 키워드는 아님. object에 Enumeration 클래스 상속받아서 구현됨
    • Scala에서는 Value의 파라미터가 Enum의 값이나 id를 지정함
      • Value의 파라미터에 따라 enum값이 전혀 달라질 수 있음
    • Scala에서 Enumeration은 자바와 달리 새로 정의된 클래스가 아니라 Value의 객체임
      object Fruits extends Enumeration {
          val APPLE: Fruits.Value = Value
          val BANANA: Fruits.Value = Value
      }
      
    • 그러다보니... 자바처럼 각 객체가 사용할 수 있는 메서드는 못만들어. 이미 Value에 지정된 메서드만 쓸 수 있을 듯
      • implicit으로 어거지로 만들수는 있어...
  • 참고로...
    • hashCode의 경우 아마 id를 bucketSize로 나눈게 아닐지....
      • override def hashCode: Int = id.##
        class EnumTest  extends PlaySpecification {
            "enum 테스트" in {
                object Fruits extends Enumeration {
                    val APPLE: Fruits.Value = Value
                    val BANANA: Fruits.Value = Value
                }
        
                println(Fruits.APPLE.hashCode()) // 0
                println(Fruits.APPLE.hashCode()) // 1
        
                Fruits.APPLE.id mustEqual 0
                Fruits.BANANA.id mustEqual 1
            }
        }
        
  • Scala Enum Value vs Val
    • Value
      • Creates a fresh value, part of this enumeration.
      • protected final def Value: Value = Value(nextId)
    • Val
      • A class implementing the scala.Enumeration.Value type.
      • This class can be overridden to change the enumeration's naming and integer identification behaviour.
      • protected class Val(i: Int, name: String) extends Value with Serializable {}

Kafka

Thread starvation / clock leap detected