首页 > 解决方案 > 不同类型的类的不同方法 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
  }
}

标签: scalagenerics

解决方案


.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


推荐阅读