我试图以通用方式对包括集合在内的大多数scala类型实现SemiGroup。但是当涉及到集合时,我被困于为集合实现隐式SemiGroupImplicitTypes。
例如:如果我要实现SemiGroup [List [T]],则期望List中元素类型的另一个参数,我不想实现SemiGroup [List [Int]],SemiGroup [List [Double]]分别,希望有一个隐式实现,它将对所有类型的List都实现。
trait Semigroup[T] extends Any {
def combine(a: T, b: T): T
}
object SemiGroup {
def apply[T](a: T, b: T)(implicit ev: Semigroup[T]): T = ev.combine(a,b)
}
class SemiGroupList[T] extends Semigroup[List[T]] {
override def combine(a: List[T], b: List[T]): List[T] = a ++ b
}
class SemiGroupSeq[T] extends Semigroup[Seq[T]] {
override def combine(a: Seq[T], b: Seq[T]): Seq[T] = a ++ b
}
class SemiGroupMap[U, V] extends Semigroup[Map[U,V]] {
override def combine(a: Map[U, V], b: Map[U, V]): Map[U, V] = a ++ b
}
class SemiGroupNumber[@specialized (Int, Double, Float, Long) T](implicit numeric: Numeric[T]) extends Semigroup[T] {
override def combine(a: T, b: T): T = numeric.plus(a, b)
}
object SemiGroupImplicitTypes {
implicit object IntSemiGroup extends SemiGroupNumber[Int]
implicit object LongSemiGroup extends SemiGroupNumber[Long]
implicit object DoubleSemiGroup extends SemiGroupNumber[Double]
implicit object FloatSemiGroup extends SemiGroupNumber[Float]
}
import SemiGroupImplicitTypes._
SemiGroup[Long](1,2)
答案 0 :(得分:1)
使其具有清晰度:
implicit def semigroupList[T] = new SemiGroupList[T]
答案 1 :(得分:1)
您需要使用类型参数实现defs:
[a,b] = deal(1,2)
答案 2 :(得分:0)
trait Semigroup[T] extends Any {
def combine(a: T, b: T): T
}
object SemiGroup {
def apply[T](a: T, b: T)(implicit ev: Semigroup[T]): T = ev.combine(a,b)
}
class SemiGroupList[T] extends Semigroup[List[T]] {
override def combine(a: List[T], b: List[T]): List[T] = a ++ b
}
class SemiGroupSeq[T] extends Semigroup[Seq[T]] {
override def combine(a: Seq[T], b: Seq[T]): Seq[T] = a ++ b
}
class SemiGroupMap[U, V] extends Semigroup[Map[U,V]] {
override def combine(a: Map[U, V], b: Map[U, V]): Map[U, V] = a ++ b
}
class SemiGroupNumber[@specialized (Int, Double, Float, Long) T](implicit numeric: Numeric[T]) extends Semigroup[T] {
override def combine(a: T, b: T): T = numeric.plus(a, b)
}
object SemiGroupImplicitTypes {
implicit def numberSemiGroup[T](implicit numeric: Numeric[T]) = new SemiGroupNumber[T]()
implicit def listSemiGroup[T] = new SemiGroupList[T]()
implicit def mapSemiGroup[U,V] = new SemiGroupMap[U,V]()
implicit def seqSemiGroup[U] = new SemiGroupSeq[U]()
}
import SemiGroupImplicitTypes._
SemiGroup[Int](1,2)
SemiGroup[List[Int]](List[Int](1,2,3), List(2,3,5))
我使用def实现的实现的修改版本。