abstract class Template[T] {
def add(x: T, y: T): T
}
abstract class SubTemplate[T] extends Template[T] {
def unit: T
}
object Implicits_Object extends App{
implicit object StringAdd extends SubTemplate[String] {
def add(x: String, y: String) = x concat y
def unit: String = ""
}
implicit object IntAdd extends SubTemplate[Int] {
def add(x: Int, y: Int) = x + y
def unit: Int = 0
}
/**
* m是隐式对象,如果T是Int,则使用IntAdd这个隐式对象
* 如果T是String,则使用StringAdd这个隐式对象
*/
def sum[T](xs: List[T])(implicit m: SubTemplate[T]): T =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail)) //tail:除了第一个元素的所有元素
println(sum(List(1, 2, 3)))
println(sum(List("a", "b", "c")))
}scala进阶18-隐式对象
最新推荐文章于 2022-04-07 17:52:41 发布
本文介绍了一个Scala中的抽象类模板,并通过具体的隐式对象实现不同类型的数据加法操作。利用泛型与隐式转换特性,实现了针对不同类型的统一接口调用。
2120

被折叠的 条评论
为什么被折叠?



