Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Step 0: 型のない世界

型情報が失われると何が起きるか、体感してみよう。

0-1. 何でも入るリスト

// step0.scala
@main def step0(): Unit =
  // In Scala, you can't omit type parameters.
  // But you can use Any to make a list that holds everything.
  val xs: List[Any] = List(100, "hello", true, 3.14)

  // What do you get when you pull something out?
  val first: Any = xs.head  // It's 100... but the type is Any

  // Try to do arithmetic — compile error
  // val doubled = first * 2
  // [error] value * is not a member of Any
  // [error]    val doubled = first * 2
  // [error]                  ^^^^^^^

  println(first)            // prints 100
  println(first.getClass)   // class java.lang.Integer

試してみよう:

> scala-cli run step0.scala

first * 2 のコメントを外してコンパイルしてほしい。エラーを読もう。 コンパイラは Any* メソッドがないと言う。

ポイント: 実行時には値は 100 が、コンパイラはそれを知らない。 型情報が失われた瞬間、コンパイラはもう守ってくれない。