加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:实现Numeric的子类型[T]

发布时间:2020-12-16 19:19:38 所属栏目:安全 来源:网络整理
导读:如何实现Numeric [T]的子类型? 我一直在寻找这方面的指南,但没有找到任何. 子类型的例子可能是Rational还是Complex? 提前致谢 特勒尔斯 解决方法 绝对无用的字符串数字: trait StringIsNumeric extends Numeric[String] { def plus(x: String,y: String):
如何实现Numeric [T]的子类型?
我一直在寻找这方面的指南,但没有找到任何.
子类型的例子可能是Rational还是Complex?

提前致谢
特勒尔斯

解决方法

绝对无用的字符串数字:

trait StringIsNumeric extends Numeric[String] {
  def plus(x: String,y: String): String = "%s+%s" format (x,y)
  def minus(x: String,y: String): String = "%s-%s" format (x)
  def times(x: String,y: String): String = "%s*%s" format (x,y)
  def quot(x: String,y: String): String = "%s/%s" format (x,y)
  def rem(x: String,y: String): String =  "%s%%s" format (x,y)
  def negate(x: String): String = "-%s" format (x)
  def fromInt(x: Int): String = x.toString
  def toInt(x: String): Int = 0
  def toLong(x: String): Long = 0L
  def toFloat(x: String): Float = 0.0f
  def toDouble(x: String): Double = 0.0
}
implicit object StringIsNumeric extends StringIsNumeric with Ordering.StringOrdering


def x[T: Numeric](t1 : T,t2 : T)  = {
  val n = implicitly[Numeric[T]]
  import n._
  t1 * t2
}
scala> x("a","b")
res0: java.lang.String = a*b

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读