あっTypoだ
case classとeq
何がしたいのかよくわからないんだけど。case classをなんとなく眺めてみた。
eqはAnyRefのメソッドで、case classに備わっていないので、普通にoverrideしてもエラーになる
http://www.scala-lang.org/api/current/index.html#scala.AnyRef
scala> case class A1(id: Int, name: String); val a1 = A1; val a2 = A1; a1 eq a2 defined class A1 a1: A1.type = A1 a2: A1.type = A1 res4: Boolean = true scala> case class A1(id: Int, name: String) { | def eq(a: Int): Boolean = a == id | } defined class A1 scala> case class A1(id: Int, name: String) { | override def eq(a: Int): Boolean = a == id | } <console>:11: error: method eq overrides nothing override def eq(a: Int): Boolean = a == id ^
というか、考えてみると、eqを定義してもAnyRefのeqが呼ばれるので、結構つらいことになるのだった。
implicit class
Implicit Classes - Scala Documentation
やっていることは、クラスのプライマリコンストラクタに、メソッドを追加する。
ここではStringに新しいメソッドを提供してる。
scala> implicit class Hoge(str: String) { | private def alpha13(c: Char): Char = c match { | case c if c.toString.matches("[A-Za-z]") && c.toLower <= 'm' => (c.toInt + 13).toChar | case c if c.toString.matches("[A-Za-z]") && c.toLower >= 'm' => (c.toInt - 13).toChar | case _ => c | } | | def rot13(): String = { | str.map(c => alpha13(c)) | } | } defined class Hoge scala> "hoge" rot13 warning: there was one feature warning; re-run with -feature for details res7: String = ubtr