kmizuの日記

プログラミングや形式言語に関係のあることを書いたり書かなかったり。

Scalaでコンパイル時アサーション

以前にMetaScalaで見かけて、なるほどーと思ったテクニック。実装は非常に簡単。

scala> type assertEq[A, B >: A <: A] = Nothing

たったこれだけ。説明は不要だと思うが、Scalaだと、型パラメータのlower boundとupper boundの両方を指定できる事を利用して、BはAのサブタイプかつスーパータイプでなければならないという指定によって、型Aと型Bが等しい事をassertしている。使い方は以下のような感じ。

scala> type x = assertEq[Int, Int]
defined type alias x

scala> type x = assertEq[Int, String]
<console>:5: error: type arguments [Int,String] do not conform to type assertEq'
s type parameter bounds [A,B >: A <: A]
       type x = assertEq[Int, String]

まあ、普通にScalaでプログラミングしている分にはまず使う機会は無いと思うけど。