2017-04-14 8 views
1

私はapache tinkerpopグラフにマップしたケースクラスで等しいかどうかのチェックに問題がありますが、グラフを照会した後で同等かどうかを確認したい。データベースから読み込んだ場合のスカラケースクラスの等価性

@label("apartment") 
case class Apartment(@id id: Option[Int], address: String, zip: Zip, rooms: Rooms, size: Size, price: Price, link: String, active: Boolean = true, created: Date = new Date()) {} 
val ApartmentAddress = Key[String]("address") 

Await.result(result, Duration.Inf).foreach(apt => { 
    val dbResult = graph.V.hasLabel[Apartment].has(ApartmentAddress, apt.address).head().toCC[Apartment] 
    println(dbResult == apt) //always false :(
    }) 

私の問題は、オブジェクトを作成したときにIDがなく、タイムスタンプが明らかに異なることです。 I 2番目のパラメータリストを追加する場合、それはイコールから除外されていることを読んで、私はそれを変更:

@label("apartment") 
case class Apartment(address: String, zip: Zip, rooms: Rooms, size: Size, price: Price, link: String, active: Boolean = true)(@id implicit val id: Option[Int] = None, implicit val created: Date = new Date()) {} 
val ApartmentAddress = Key[String]("address") 

Await.result(result, Duration.Inf).foreach(apt => { 
    val dbResult = graph.V.hasLabel[Apartment].has(ApartmentAddress, apt.address).head().toCC[Apartment] 
    println(dbResult == apt) //true! yay! :D 
    }) 

私は今、==を使用して等価性をチェックすることができますが、データベースからの値はそのIDを失い、 「作成された」値がリセットされます。そして、一つの他のイライラ事は、彼らは常に最後に余分な括弧を使用して作成する必要があります等号の過負荷をせずにこの機能を実現する方法は

Apartment(address, zip, rooms, size, price, link)() 

ありますか?または、このアプローチを使用してデータベースからの値を元の値に維持しますか?

それはあなたのケースで思わ

答えて

3

、あなただけの一度だけの比較のためにそれを必要とするので、私はイコールで遊ぶだけ変更された値の比較

case class Apartment(
    @id id: Option[Int] = None, 
    address: String, 
    zip: Zip, 
    rooms: Rooms, 
    size: Size, 
    price: Price, 
    link: String, 
    active: Boolean = true, 
    created: Date = new Date(0)) { 
} 

println(dbResult.copy(id = None, created = new Date(0)) == apt) //true! yay! :D 

上またはクラスに余分な機能を追加しないでしょう

case class Apartment(
    @id id: Option[Int] = None, 
    address: String, 
    zip: Zip, 
    rooms: Rooms, 
    size: Size, 
    price: Price, 
    link: String, 
    active: Boolean = true, 
    created: Date = new Date(0)) { 

    def equalsIgnoreIdAndCreated(other: Apartment) = { 
     this.equals(other.copy(id = id, created = created)) 
    } 
} 

println(dbResult.equalsIgnoreIdAndCreated(apt)) 

http://www.alessandrolacava.com/blog/scala-case-classes-in-depth/のケースクラスの説明と、自動的に生成されたequalsをオーバーライドしないようにする理由を確認できます。それ以外の場合はequalsをオーバーライドしてください。

+0

完璧!ありがとうございました! – Raudbjorn

関連する問題