Scala:实现数字的子类型[T] [英] Scala: Implementing a subtype of Numeric[T]

查看:90
本文介绍了Scala:实现数字的子类型[T]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现Numeric [T]的子类型? 我一直在寻找有关此的指南,但没有找到任何指南. 子类型的示例可能是Rational还是Complex?

How does one go about implementing a subtype of Numeric[T]? I have been looking for at guide on this but haven't found any. Example of subtypes could be Rational or Complex?

先谢谢了 troels

Thanks in advance Troels

推荐答案

一个绝对无用的字符串数字:

An absolutely useless String Numeric:

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

这篇关于Scala:实现数字的子类型[T]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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