Can an object infer an overridden field's type from a trait?
I am generating some test data as follows:
trait Template {
val field1: Map[List[String], Map[Int, List[Boolean]]] //the type is for illustration. Think of it as a 'monstrous type definition'
val field2: Map[List[Int], Map[Double, List[Option[String]]]]
}
object Fixture extends Template {
override val field1 = Map()
override val field2 = Map()
}
This fails with the message value field1 has incompatible type
, ditto for field2
?
I can fix it by providing types in Fixture
explicitly, but I am trying to avoid this because if I change a type inside the trait I will need to propagate it to every fixture object.
Can my object Fixture
infer the types for field1
and field2
from trait Template
.
I don't know why the compiler isn't smart enough to infer the right type for a val
, but it will for a def
. You can get around the problem by putting the initialization code into a def.
trait Template {
val field1 = field1Init
def field1Init: Map[List[String], Map[Int, List[Boolean]]]
val field2 = field2Init
def field2Init: Map[List[Int], Map[Double, List[Option[String]]]]
}
object Fixture extends Template {
override def field1Init = Map()
override def field2Init = Map()
}
链接地址: http://www.djcxy.com/p/20760.html
上一篇: Javascript母语文本