Pixel Pedals of Tomakomai

北海道苫小牧市出身の初老の日常

Unit への implicit conversion

内容はともかく気になったのが、

  def A_B_Cのつもりで書いた間違っているのにビルドが通る例(): Future[Unit] = {
    funcA()
      .map { _ =>funcB()}
      .map { _ =>funcC()}
    // ※たとえでこう書いていますが、本来はfor文とかを使いましょう
    // ※返値の型は本当はFuture[Future[Unit]]です。
  }

《Scala》Future[Unit]は気をつけて使おうの話

がなんでコンパイル通るのかなと思って *1 、 sub typing や ビルトインで定義されている implicit conversion を疑ってたんだけど、 Unit に関するものは見つからず、なんでだろうと。

答えは、単純に言語仕様だから、だった。

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }. https://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html

*1:コメントの型も正しい意味なのやら