Tim
Tim

Reputation: 2028

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.

Upvotes: 7

Views: 119

Answers (1)

wingedsubmariner
wingedsubmariner

Reputation: 13667

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() 
}

Upvotes: 3

Related Questions