복붙노트

[SCALA] 스칼라 : 같음 / 해시 코드를위한 경우 클래스 필드를 무시?

SCALA

스칼라 : 같음 / 해시 코드를위한 경우 클래스 필드를 무시?

이 경우 클래스의 같음 / 해시 코드 방식의 경우 클래스의 필드를 무시할 수 있습니까?

내 유스 케이스는 I 클래스에있는 데이터의 나머지 부분에 대한 본질적으로 메타 데이터 인 필드를 가지고있다.

해결법

  1. ==============================

    1.첫 번째 매개 변수 섹션에서 매개 변수 만은 평등과 해시에 대한 간주됩니다.

    첫 번째 매개 변수 섹션에서 매개 변수 만은 평등과 해시에 대한 간주됩니다.

    scala> case class Foo(a: Int)(b: Int)
    defined class Foo
    
    scala> Foo(0)(0) == Foo(0)(1)
    res0: Boolean = true
    
    scala> Seq(0, 1).map(Foo(0)(_).hashCode)
    res1: Seq[Int] = List(-1669410282, -1669410282)
    

    최신 정보

    필드로 B를 노출하려면 :

    scala> case class Foo(a: Int)(val b: Int)
    defined class Foo
    
    scala> Foo(0)(1).b
    res3: Int = 1
    
  2. ==============================

    2.

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    case class Foo private(x: Int, y: Int) {
      def fieldToIgnore: Int = 0
    }
    
    object Foo {
      def apply(x: Int, y: Int, f: Int): Foo = new Foo(x, y) {
        override lazy val fieldToIgnore: Int = f
      }
    }
    
    // Exiting paste mode, now interpreting.
    
    defined class Foo
    defined module Foo
    
    scala> val f1 = Foo(2, 3, 11)
    f1: Foo = Foo(2,3)
    
    scala> val f2 = Foo(2, 3, 5)
    f2: Foo = Foo(2,3)
    
    scala> f1 == f2
    res45: Boolean = true
    
    scala> f1.## == f2.##
    res46: Boolean = true
    

    필요한 경우로 .toString를 오버라이드 (override) 할 수 있습니다.

  3. ==============================

    3.당신이 경우 클래스의 equals 메소드와 hashCode 메소드를 재정의 할 수 있습니다

    당신이 경우 클래스의 equals 메소드와 hashCode 메소드를 재정의 할 수 있습니다

    scala> :paste
    // Entering paste mode (ctrl-D to finish)
    
    case class Person( val name:String, val addr:String) {
      override def equals( arg:Any) = arg match {
        case Person(s, _) => s == name
        case _ => false
      }
      override def hashCode() = name.hashCode
    }
    
    // Exiting paste mode, now interpreting.
    
    scala> Person("Andy", "") == Person("Andy", "XXX")
    res2: Boolean = true
    
    scala> Person("Andy", "") == Person("Bob", "XXX")
    res3: Boolean = false
    
  4. ==============================

    4.당신이 기본 클래스에있는 toString를 오버라이드 (override)하는 경우는 파생 된 경우 클래스에 의해 오버라이드 (override)되지 않습니다. 다음은 그 예이다 :

    당신이 기본 클래스에있는 toString를 오버라이드 (override)하는 경우는 파생 된 경우 클래스에 의해 오버라이드 (override)되지 않습니다. 다음은 그 예이다 :

    sealed abstract class C {
      val x: Int
      override def equals(other: Any) = true
    }
    
    case class X(override val x: Int) extends C
    
    case class Y(override val x: Int, y: Int) extends C
    

    테스트 우리보다 :

    scala> X(3) == X(4)
    res2: Boolean = true
    
    scala> X(3) == X(3)
    res3: Boolean = true
    
    scala> X(3) == Y(2,5)
    res4: Boolean = true
    
  5. from https://stackoverflow.com/questions/10373715/scala-ignore-case-class-field-for-equals-hascode by cc-by-sa and MIT license