0

I would like subclasses to inject functionality within the base class' apply method:

Base class:

case class BaseClass(data: Json)

object BaseClass {
  def apply(data: String) : JsonClass = {
    try {
      _ //subclass functionality should go here
    } catch {
      case e: Exception => ErrorJsonClass(data)
    }
  }
}

object SubClass extends BaseClass {
  def apply(data: String) : Json = {
    deserialize(data) // this should be called within the base class' apply
  }
}

Is there a way to do this without declaring separate methods within the base class?

Ie. Im trying to avoid the following:

object BaseClass {
  def apply(data: String) : JsonClass = {
    try {
      convert(data)
    } catch {
      case e: Exception => ErrorJsonClass(data)
    }
  }

  def convert(data: String): JsonClass = _
}

object SubClass extends BaseClass {
  def convert(data: String) : Json = {
    deserialize(data) 
  }
}
autodidacticon
  • 1,310
  • 2
  • 14
  • 33
  • Possible duplicate of [Is there any way to extend an object?](http://stackoverflow.com/questions/7625040/is-there-any-way-to-extend-an-object) – Tyth Nov 09 '15 at 16:18
  • 2
    Why would you like to avoid "the following"? "The following" is exactly what you should do, only instead of doing `def convert(data: String): JsonClass = _`, you should declare it abstract, i.e. `def convert(data: String): JsonClass` (no implementation) – Zoltán Nov 09 '15 at 16:44

0 Answers0