scala - 不同类型的类的不同方法 toString
问题描述
对于字符串和数字(Int、Double、Float),我需要让方法 toString 不同。对于字符串,它只是转换为字符串,对于数字,它将列表的每个元素乘以数字并转换为字符串。当我试图让它至少对 Int 起作用时,它会说“方法 'toString' 不会覆盖任何内容”。
class Seq[T : Ordering] (initialElems: T*) {
override def toString(implicit ev: T <:< Int): String = {
elems.foreach((i:T) => fac(factors)*i).toString
}
val elems = initialElems.sorted
def concat(a:Seq[T]) = new Seq(a.elems ++ this.elems:_*)
val factors = ListBuffer[Int](1)
def fac(xs: ListBuffer[Int]): Int = {
var i=0
var sum = 1
while (i < xs.length) {
sum *= xs(i)
i += 1
}
sum
}
def multy(a: Int)(implicit ev: T <:< AnyVal): Unit = {
factors += a
}
}
解决方案
.foreach
返回Unit
,所以它应该是.map
。
尝试定义一个类型类并将隐式参数从方法级别传递到类级别
trait ToStr[T] {
def apply(factors: ListBuffer[Int], fac: ListBuffer[Int] => Int, elems: T*): String
}
object ToStr {
implicit val int: ToStr[Int] =
(factors, fac, elems) => elems.map((i: Int) => fac(factors) * i).toString
implicit val str: ToStr[String] = (_, _, elems) => elems.toString
}
class Seq[T : Ordering] (initialElems: T*)(implicit toStr: ToStr[T]) {
override def toString: String = toStr(factors, fac, elems: _*)
...
}
否则def toString(implicit ev: T <:< Int): String
确实不会覆盖def toString: String
。
推荐阅读
- python - 为什么 Pandas 应用函数返回无
- reactjs - React Redux Hooks 找不到状态
- javascript - javascript for 循环中的异步/等待
- deployment - 是否有可能在 CDN 上部署无头 CMS?
- python - 减少python中的if语句
- javascript - 是否可以在本地网络/热点中设置 websocket 服务器(android/ios)并通过 PWA 连接?
- java - How can I change the TextView's content by swiping horizontally?
- python-3.x - 使用 Selenium 从交互式地图中刮取图钉坐标
- scripting - adb emu kill - 等待模拟器被完全杀死
- javascript - 如何将每个对象存储在循环中?