Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package jp.takeda_soft.examples
/**
世界のナベアツに挑戦
テーマ:implicitによるScalaAPIの拡張
*/
object Nabeatsu extends Application {
//Intがバカになるメソッド"!"を追加
implicit def bakanize(n: Int) = new Bakanizer(n)
//Int.!を1から40まで表示(99までどうぞ)
//あえてyieldでワンクッション
var nums = for( i <- 1 to 40 ) yield i!
for( n <- nums ) println( n )
}
/**
Ruby風 to_s, to_i を拡張実装(適当です)
もっとscala風な実装があるのではないだろうか。
*/
class Rubynizer(n:Any) {
def to_s = n.toString
def to_i = {
if( n.isInstanceOf[Char] ) n.asInstanceOf[Char].toString.toInt
else if( n.isInstanceOf[String] ) n.asInstanceOf[String].toInt
else throw new NumberFormatException()
}
}
/**
Intがバカになる拡張クラス
*/
class Bakanizer(n:Int) {
/** Ruby風メソッドの導入 */
implicit def rubynize(n:Any) = new Rubynizer(n)
/** なべあつ変換 */
def ! = baka(n)
/** ! の実装 */
private def baka(n: Int): String = {
if( n < 10 ) if( n % 3 == 0 ) ichi(n) else n.to_s
else if( n < 99 ){
val s = n.to_s
val k2 = s(0).to_i
val k1 = s(1).to_i
if( n % 3 == 0 || k2 == 3 || k1 == 3 ) ju(k2) + ichi(k1)
else s
}else throw new Exception("2桁まで")
}
private val ju:List[String]
= List("","じゅ~","に~じゅ","さぁ~んじゅ","よぉ~んじゅ"
,"ごぉ~じゅ","ろぉくじゅ","しぃちじゅ","はぁ~ちじゅ","きゅ~じゅ")
private val ichi:List[String]
= List("","えぃち","にぃ","さぁん","しぃ","ごぉ"
,"ろぉく","ひぃち","はぁち","きゅ~")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment