Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an object infer an overridden field's type from a trait?

Tags:

scala

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.

like image 949
Tim Avatar asked May 29 '14 23:05

Tim


1 Answers

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() 
}
like image 155
wingedsubmariner Avatar answered Sep 24 '22 18:09

wingedsubmariner