13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

大小比較の可能なcase class

Last updated at Posted at 2015-01-27

こういうことがしたい。

Version(1, 0, 0) > Version(0, 9, 0)

で、こんなふうにやればいいんじゃないかと教えてもらったんだけど、

case class Version(major: Int, middle: Int, minor: Int)

object Version {
  import scala.math._
  implicit val ordering: Ordering[Version] = Ordering.by(v => (v.major, v.middle, v.minor))
  implicit def orderingToOrdered(v: Version) = Ordered.orderingToOrdered(v)(ordering)
}

ちょっと黒魔術っぽくてもっといい方法無いのかなーとか思って考えたら、こういうのを思いついた。

case class Version(major: Int, middle: Int, minor: Int) extends Ordered[Version] {
  import scala.math.Ordered._

  def compare(that: Version): Int = {
    (major, middle, minor).compare((that.major, that.middle, that.minor))
  }
}

最初の方法と違って、等号を持つcase classの拡張として不等号を持つOrderedがくっついているんですよということが一目で分かることが良いと思う。

(major, middle, minor)(that.major, that.middle, that.minor)という似た記述を2回やってるのはイケてないけど。

13
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?