【发布时间】:2017-06-28 15:34:20
【问题描述】:
Scala 是否有对象的隐式转换?例如,如果我有一个具有以下签名的方法:
object Foo {
def print(message: String) = println(message)
}
class Bar {
val baz = 1
}
如何拨打Foo.print(new Bar)?
我可以在Bar 类上放置一个方法来将Bar 实例隐式转换为字符串,而不必在参数中调用toString?
C# 有这个,我想知道 scala 是否也有。
假设我们有 Scala 枚举:
object Color extends Enumeration {
type Method = Value
val RED, BLUE, GREEN = Value
}
那我有课了:
object ColorPrinter {
def print(x: String) = {
println(x)
}
}
ColorPrinter 的打印方式无法更改。
我想打电话给ColorPrinter.print(Color.RED),但我不能这样做。我必须这样称呼它:ColorPrinter.print(Color.RED.toString)。
我想避免toString
【问题讨论】:
-
出于可读性原因,通常不鼓励使用隐式自动全局转换
标签: scala