Tom
Tom

Reputation: 6342

It looks like type inference does't work here

I have following code:

trait A {
  def x: Option[Int]
  def y: Option[String]
}

case class A1(
    override val x: Option[Int] = Some(1),
    override val y: Option[String] = Some("abc")
) extends A

case class A2() extends A {
  override val x = Some(1)
  override val y = Some("abc")
}

In the definition of A1, I have to specify x and y's type, which are Option[Int] and Option[String],

x: Option[Int] and val y: Option[String]

but I don't have to specify the type for A2

Could some one help why I have to for A1, and not for A2?

Upvotes: 0

Views: 44

Answers (1)

Stephen Carman
Stephen Carman

Reputation: 997

That is because you are creating your overridden values of trait A inside the case classes' constructor. In A2 you override them in the class body, which makes them just like any other class member. Remember that you couldn't write something like this

case class A1(val x = Some(1), val y = Some("Asdf")) extends A

because you are required to give types to your constructor parameters, so it's just normal Scala (and programming in general) semantics that are why you cannot do what you are trying to do.

Upvotes: 2

Related Questions