I have some generic/OOP Scala code (not useful, just classroom excercises)
I have a Container interface, "IterableContainer", that takes in and returns objects whose type is a subclass of AnyRef. It has a concrete sub-class that also takes in and returns objects whose type is a subclass of AnyRef.
trait IterableContainer[Type <: AnyRef] {
def length: Int
def getAt(index: Int): Type
def append(element: Type)
}
class IterableArrayList[T <: AnyRef]() extends IterableContainer[T] {
val underlyingContainer = new ArrayBuffer[T](16)
override def length: Int = {
return underlyingContainer.length
}
override def getAt(index: Int): T =
{
if (index < underlyingContainer.length) {
return underlyingContainer(index)
} else {
return null // Expression of type T does not conform to expected type.
}
}
override def append(element: T) = {
underlyingContainer :+ element // :+ means append
}
}
Can anyone explain why I cannot return null when T is explicitly being stated as a an object of a type that extends AnyRef?
Also, if you understand Scala's generics better than I do, please explain further - they really make no sense to me (relative to C++ generics).