Search code examples
scalascala-option

Override toString behavior for Option[_] in scala


I would prefer to see just the value of the Option (if it were not None) , instead of the following additional Some() noise:

List((Some(OP(_)),Some(share),3), (Some(OP(D)),Some(shaara),4), (Some(OP(I)),Some(shaaee),4))

Now, I could write a method that handles this for List[Option[_]] .. But there are many other structures in which Options appear - so this approach of addressing explicitly each one is cumbersome.

Due to implicits having lower precedence the following code simply gets ignored:

  implicit def toString(myopt : Option[_]) = if (myopt == None) "None" else myopt.get

The concern is that - although implementing for example a toString(List[Option_]]) method that handles this in the desired manner, that is still a one-off. What about a

Map[Option,Option]  =>     def toString(Map[Option,Option]) = { .. }

It seems We would still need to implement an explicit toString() for each collection type..


Solution

  • Following takes care of the cases that came to mind:

      def show(obj: Any) : String = {
        obj match {
          case o: Option[_] =>
            if (o == None) {
              "<none>"
            } else {
              show(o.get)
            }
          case i: Iterable[_] =>
            i.map(show).mkString("[", ",", "]")
          case m: Map[_, _] =>
            m.map {
              case (a, b) => List(show(a), show(b)).mkString(":")
            }.mkString("{", ",", "}")
          case e: Enumeration =>
            e.toString
          case c : Product if !c.getClass.getMethods.map(_.getName).contains("copy$default$2") =>
            c.toString
          case t: Product =>
            t.productIterator.map(a => show(a)).mkString("(", ",", ")")
          case _ =>
            if (obj.isInstanceOf[AnyRef])
              obj.asInstanceOf[AnyRef].toString
            else
              "" + obj
        }
      }
    

    I opted to code this up to avoid adding scalaz dependency (assuming their Show class supports similar feature)