Python風の%をScalaで

30分プログラム、その405。Pythonの文字列の%をScalaでもやってみる。

Pythonの%はこんな感じで、要するにsprintf。

>>> "Hi, %s" % "mzp"
'Hi, mzp'
>>> "The %s is %d." % ("answer",42)
'The answer is 42.'

implicit conversionを使って、Stringにメソッドを疑似的に追加することで、Scalaでも実現してみた。

使い方

scala> import FormatString._
import FormatString._

scala> "Hi, %s" % List("mzp")
res44: java.lang.String = Hi, mzp

scala> "Answer is %d" % List(int2Integer(42))
res46: java.lang.String = Answer is 42

ソースコード

class FormatString(str : String) {
  def %(args : List[AnyRef]) ={
    String.format(str,args.toArray)
  }
}

object FormatString{
  implicit def convert(str : String) : FormatString =
    new FormatString(str)
}