by shigemk2

当面は技術的なことしか書かない

implicit class

Implicit Classes - Scala Documentation

kmizu.hatenablog.com

やっていることは、クラスのプライマリコンストラクタに、メソッドを追加する。

ここでは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