How do I create an explicit companion object for a case class which behaves identically to the replaced compiler provided implicit companion object?

前端 未结 3 1260
独厮守ぢ
独厮守ぢ 2020-12-09 06:41

I have a case class defined as such:

case class StreetSecondary(designator: String, value: Option[String])

I then define an expli

3条回答
  •  醉梦人生
    2020-12-09 07:15

    When defining an explicit companion object for a case class (as of Scala 2.11), to fully replace the compiler provided functionality in the lost implicit companion object, the basic template for the explicit companion object has two requirements:

    Requirements:
    1. Must extend a function definition which consists of a tuple (exactly matching the type and order of the case class constructor parameters) returning the type of the case class
    2. Must override the toString function to provide the object class name (identical to that of the associated case class)

    Here's the original example code for the "empty" explicit companion object:

    object StreetSecondary {
      //empty for now
    }
    

    And here is the example code after implementing the above requirements:

    object StreetSecondary extends ((String, Option[String]) => StreetSecondary) {
        //replace the toString implementation coming from the inherited class (FunctionN)
        override def toString =
          getClass.getName.split("""\$""").reverse.dropWhile(x => {val char = x.take(1).head; !((char == '_') || char.isLetter)}).head
    }
    

    To meet requirement 1 above, extends ((String, Option[String]) => StreetSecondary) is inserted right after the object name and before the first curly brace.

    To meet requirement 2 above, override def toString = getClass.getName.split("""\$""").reverse.dropWhile(x => {val char = x.take(1).head; !((char == '_') || char.isLetter)}).head is inserted in the body of the object (the explicit implementation remains questionable)

    Deep appreciation to @drstevens for his posting the javap output to help me gain confidence the above two steps are all that are required to restore the lost functionality.

提交回复
热议问题