在 Scala 中,是否可以使用隐式来自动覆盖 toString? [英] In Scala, is it possible to use implicits to automatically override toString?

查看:44
本文介绍了在 Scala 中,是否可以使用隐式来自动覆盖 toString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我会做类似的事情

In Java, I would do something like

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

MyDate date = new MyDate

有点笨重.在 Scala 中,是否可以在仍然使用常规 java.util.Date 而不是 MyDate 的同时覆盖 toString.我有一个隐含的暗示,但很乐意使用任何技术

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

推荐答案

隐式转换只有在被转换的类型还没有具有给定签名的方法时才有效.由于所有东西都有一个 toString,因此不可能通过拉皮条来覆盖它.

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.

您可能要做的是使用如下所示的类型类(类似于 scalaz.Show):

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

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

然后你可以在任何地方使用 show 而不是 toString.理想情况下,您想要的是使 Show[Any] 实例成为一个非常低的隐式优先级.

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.我不建议使用 scalaz.Show 的原因是返回类型是 List[Char],这对于大多数用途来说是不切实际的

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

这篇关于在 Scala 中,是否可以使用隐式来自动覆盖 toString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆