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
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.
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.
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.
Overriding toString to be able to print out the object in a readable way when it is later read from the file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With