Dominika
Dominika

Reputation: 185

Override methods from traits in case objects

I have a trait and two case objects. Both case objects have an almost identical method which utilises one unique method from the case object. I want to extract the identical method and place it in the trait. I am unsure how to do that with the unique methods it takes in as arguments. Code example:

sealed trait Book {}

case object Page extends Book {
def a(): UniqueToPage = println("Page")
def shared(contents: String) = println(s"Something shared and ${a()} and $contents") 
}

case object Cover extends Book {
def b(): UniqueToCover = println("Cover")
def shared(contents: String) = println(s"Something shared and ${b()} and $contents")
}

It seems to me that perhaps there is something I could do with type conversion but I am at loss as to where to start. Any suggestions would be greatly appreciated. Please note that the design is part of a larger project and I am trying to refactor this specific part.

Upvotes: 1

Views: 159

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

If methods a() and b() return different types UniqueToPage and UniqueToCover try to introduce type member

sealed trait Book {
  type T
  def c(): T
  def shared(contents: String) = println(s"Something shared and ${c()} and $contents")
}

case object Page extends Book {
  override type T = UniqueToPage
  override def c(): T = println("Page")
}

case object Cover extends Book {
  override type T = UniqueToCover
  override def c(): T = println("Cover")
}

Upvotes: 3

Related Questions