您的位置:首页 > 编程语言

Scala中隐式对象代码实战详解之Scala学习笔记-54

2015-09-16 08:21 399 查看
package com.leegh.implicits

/**
* @Tuthor Guohui Li
*/
abstract class Template[T] {
def add(x: T, y: T): T
}

abstract class SubTemplate[T] extends Template[T] {
def unit: T
}

object Implicits_Object {

def main(args: Array[String]): Unit = {
implicit object StringAdd extends SubTemplate[String] {
def add(x: String, y: String): String = x concat y
def unit: String = ""
}
implicit object IntAdd extends SubTemplate[Int] {
def add(x: Int, y: Int): Int = x + y
def unit: Int = 0
}
def sum[T](xs: List[T])(implicit m: SubTemplate[T]): T =
if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))
println(sum(List(1, 2, 3, 4, 5)))
println(sum(List("a", "b", "c")))
}
}

附:

本博客说明:

1.整理思路,提高自己。

2.受教于王家林老师,​有所收获,故推荐。

3.博客注重实践,多余的文字就不多说了,都是做技术的。

4.信息来源于 DT大数据梦工厂微信公众账号:DT_Spark。​

DT大数据梦工厂的微信公众号是DT_Spark,每天都会有大数据实战视频发布,请您持续学习。

王家林DT大数据梦工厂scala的所有视频、PPT和代码在百度云盘的链接:http://pan.baidu.com/share/home?uk=4013289088#category/type=0&qq-pf-to=pcqq.group

王家林《Scala深入浅出实战初级入门经典视频课程》http://edu.51cto.com/lesson/id-66538.html

王家林《Scala深入浅出实战中级进阶经典视频课程》http://edu.51cto.com/lesson/id-67139.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: