リテラル

複数行文字列リテラル

Scalaでは複数行の文字列リテラルを"""で表します。

object Main extends Application {
  val str1 = """the present string
    spans three
    lines."""
  println(str1)
}

とすると、

the present string
    spans three
    lines.

このように表示されます。


これだとインデント部分がそのまま表示されるので、その場合は、

object Main extends Application {
  val str2 = """the present string
    |spans three
    |lines.""".stripMargin
  println(str2)}

とすると、

the present string
spans three
lines.

と表示されます。

XMLリテラル

ScalaではXMLを直接リテラルとして記述できます。

class Scala(v:String){ def version = v }

object Example022 extends Application {
  val scala = new Scala("1.00")
  val b = <book>
    <title>The Scala Language Specification</title>
    <version>{scala.version}</version>
  </book>
  println(b.getClass)
  println(b.text)
}

実行結果は、

class scala.xml.Elem

    The Scala Language Specification
    1.00

リテラルXMLとして解釈されていることがわかります。また、{}で記載した内容が展開されていることにも注目してください。

シンボルリテラル

シンボルリテラルは、'で開始するリテラルです。以下のように記載します。

object Main extends Application {
  val str = 'Test
  println(str.getClass)
}

実行結果は以下のようになります。

Test
class scala.Symbol

シンボルリテラルは、scala.Symbolをインスタンス化する簡素な記述方法を提供しています。
scala.Symbolは、内部で文字列を弱参照オブジェクトとしてキャッシュしているケースクラスとして実装されています。そのため、シンボルリテラルのオブジェクトは、参照の同一性が確実なものとなります。