by shigemk2

当面は技術的なことしか書かない

上限境界と下限境界のメモ

Scalaジェネリクスメモ(Hishidama's Scala parameterized type Memo)

上限境界と下限境界を試してみて、どうなるのかをここに書き留めておく。

scala> class A1
defined class A1

scala> class A2 extends A1
defined class A2

scala> class A3 extends A2
defined class A3

scala> class Example[T]
defined class Example

scala> new Example[Any]
res0: Example[Any] = Example@18ef96

scala> new Example[A1]
res1: Example[A1] = Example@3834d63f

scala> new Example[A2]
res2: Example[A2] = Example@1d251891

scala> new Example[A3]
res3: Example[A3] = Example@42d3bd8b

scala> new Example[Nothing]
res4: Example[Nothing] = Example@337d0578

scala> class Example[T <: A2]
defined class Example

scala> new Example[Any]
<console>:13: error: type arguments [Any] do not conform to class Example's type parameter bounds [T <: A2]
       val res5 =
           ^
<console>:14: error: type arguments [Any] do not conform to class Example's type parameter bounds [T <: A2]
       new Example[Any]
           ^

scala> new Example[A1]
<console>:13: error: type arguments [A1] do not conform to class Example's type parameter bounds [T <: A2]
       val res6 =
           ^
<console>:14: error: type arguments [A1] do not conform to class Example's type parameter bounds [T <: A2]
       new Example[A1]
           ^

scala> new Example[A2]
res7: Example[A2] = Example@14bf9759

scala> new Example[A3]
res8: Example[A3] = Example@66480dd7

scala> new Example[Nothing]
res9: Example[Nothing] = Example@551aa95a

scala> class Example[T >: A2]
defined class Example

scala> new Example[Any]
res10: Example[Any] = Example@2a556333

scala> new Example[A1]
res11: Example[A1] = Example@1a3869f4

scala> new Example[A2]
res12: Example[A2] = Example@4fb64261

scala> new Example[A3]
<console>:14: error: type arguments [A3] do not conform to class Example's type parameter bounds [T >: A2]
       val res13 =
           ^
<console>:15: error: type arguments [A3] do not conform to class Example's type parameter bounds [T >: A2]
       new Example[A3]
           ^

scala> new Example[Nothing]
<console>:13: error: type arguments [Nothing] do not conform to class Example's type parameter bounds [T >: A2]
       val res14 =
           ^
<console>:14: error: type arguments [Nothing] do not conform to class Example's type parameter bounds [T >: A2]
       new Example[Nothing]
           ^