Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, is it possible to use implicits to automatically override toString?

Tags:

scala

In Java, I would do something like

class MyDate extends java.util.Date {
  public String toString() { ... }
}

MyDate date = new MyDate

A little bit clunky. In Scala, is it possible to override toString whilst still using regular java.util.Date instead of MyDate. I have an inkling implicits are involved but would be happy to use any technique

like image 299
deltanovember Avatar asked Aug 04 '11 10:08

deltanovember


People also ask

How do I override toString method in Scala?

Overriding toString() method in Scala The object class has some basic methods like clone(), toString(), equals(), .. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output.

How implicits work in Scala?

The implicit system in Scala allows the compiler to adjust code using a well-defined lookup mechanism. A programmer in Scala can leave out information that the compiler will attempt to infer at compile time. The Scala compiler can infer one of two situations: A method call or constructor with a missing parameter.

How to use toString in Scala?

Scala Int toString() method with example The toString() method is utilized to return the string representation of the specified value. Return Type: It returns the string representation of the specified value.

Why is it needed to override toString () method in a DTO class?

Overriding toString to be able to print out the object in a readable way when it is later read from the file.


1 Answers

Implicit conversions can only work if the type being converted does not already have a method with a given signature. As everything has a toString, it is not possible to override this by pimping.

What you might do is use a typeclass (akin to scalaz.Show) which looks like this:

trait Show[-A] {
  def show(a : A): String
}

Then you can use show everywhere instead of toString. Ideally what you want then is to make the Show[Any] instance a very low priority implicit.

implicit val DateShow = new Show[Date] { def show(d : Date) = "whatever" }

trait LowPriorityShows {
  implicit val AnyShow = new Show[Any] { def show(a : Any) = a.toString }
}

P.S. The reason I would not suggest using scalaz.Show is that the return type is List[Char], which is just not practicable for most uses

like image 129
oxbow_lakes Avatar answered Oct 14 '22 04:10

oxbow_lakes