型パラメータの範囲指定
Scalaの型パラメータでは、パラメータで受け付けるクラスの範囲を制限することができます。Javaの「super」とか「extends」みたいな機能です。
- 「[<型パラメータ名> <: <型>]」とすることで、「<型パラメータ名>は<型>派生の何か」に制限できます。
- 「[<型パラメータ名> >: <型>]」とすることで、「<型パラメータ名>は<型>またはその上位クラスの何か」に制限できます。
// テスト用クラス trait A class AA extends A class B // Aまたはその下位クラスを型パラメータとして受け取るクラス class Foo[a <: A] {} //Aまたはその上位クラスを型パラメータとして受け取るクラス class Var[a >: A] {} // クラスを使うサンプル object Sample { def main(args: Array[String]) { new Foo[A] // OK new Foo[AA] // OK new Foo[B] // これはエラー new Foo[Object] // これはエラー new Var[A] // OK new Var[AA] // これはエラー new Var[B] // これはエラー new Var[Object] // OK } }
コンパイルすると、以下の通りエラーになります。
$ scalac GenericsRangeSample.scala GenericsRangeSample.scala:21: error: type arguments [B] do not conform to class Foo's type parameter bounds [a <: A] new Foo[B] // これはエラー ^ GenericsRangeSample.scala:22: error: type arguments [java.lang.Object] do not conform to class Foo's type parameter bounds [a <: A] new Foo[Object] // これはエラー ^ GenericsRangeSample.scala:25: error: type arguments [AA] do not conform to class Var's type parameter bounds [a >: A] new Var[AA] // これはエラー ^ GenericsRangeSample.scala:26: error: type arguments [B] do not conform to class Var's type parameter bounds [a >: A] new Var[B] // これはエラー ^ four errors found
ほかにも、「+」「-」とか「<%」とかが使えるらしいけど、また今度!