1.什么是Trait ?

Traits are a fundamental unit of code reuse in Scala. A trait encapsulates
method and field definitions, which can then be reused by mixing them into
classes. Unlike class inheritance, in which each class must inherit from just
one superclass, a class can mix in any number of traits.
Traits是Scala中代码复用的基本单元

类似Java中的接口,但是可以定义method和field

2. 第一个Trait, 具有哲学家特征的青蛙,哈哈

package chapter12trait Philosophical {def philosophise() = println("I consume memory, therefor I am !")
}class Frog extends Philosophical {override def toString = "green"
}object TestMain {def main(args: Array[String]) {val frog = new Frogfrog.philosophise()    //I consume memory, therefor I am !}
}

This trait is named Philosophical. It does not declare a superclass, so
like a class, it has the default superclass of AnyRef. It defines one method,
named philosophize, which is concrete.

默认继承 AnyRef

Once a trait is defined, it can be mixed in to a class using either the
extends or with keywords

用关键字: extends 或 with 将Trait混入类

You can use the extends keyword to mix in a trait; in that case you
implicitly inherit the trait’s superclass
当用extends 关键字时,该类隐式地继承了trait的父类

A trait also defines a type.

定义一个trait的同时也定义了一个新的类型

    val philo: Philosophical = new Frogphilo.philosophise()

3.显式声明父类,重载trait的方法

package chapter12trait Philosophical {def philosophise() = println("I consume memory, therefor I am !")
}class Cat class Frog extends Cat with Philosophical {override def toString = "green"override def philosophise() = println("It ain't easy to being " + toString)
}

4.At this point you might philosophize that traits are like Java interfaces
with concrete methods, but they can actually do much more. Traits can, for
example, declare fields and maintain state. In fact, you can do anything in
a trait definition that you can do in a class definition, and the syntax looks
exactly the same, with only two exceptions.
Trait可以做class可以做的所有事情,只有两点例外

第一,trait 不能包含类参数,也就是说不能有构造函数

trait Philosophical(x: Int, y: Int) {def philosophise() = println("I consume memory, therefor I am !")
}
// 编译无法通过

第二,使用super调父类方法的时候,class中是静态绑定的,trait中是动态绑定的

The other difference between classes and traits is that whereas in classes,
super calls are statically bound, in traits, they are dynamically bound. If
you write “super.toString” in a class, you know exactly which method
implementation will be invoked. When you write the same thing in a trait,
however, the method implementation to invoke for the super call is undefined when you define the trait. Rather, the implementation to invoke will
be determined anew each time the trait is mixed into a concrete class. This
curious behavior of super is key to allowing traits to work as stackable modifications

关于可堆叠的更改(stackable modification)后面会详细说明

5.再看一个例子

package chapter12class Point(val x: Int, val y: Int)trait Rectangular {def topLeft: Pointdef bottomRight: Pointdef left = topLeft.x def right = bottomRight.x def width = right - left
}abstract class Component extends Rectangularclass Rectangle (val topLeft: Point, val bottomRight: Point) extends Rectangular

这样所有的组件和矩形都有了Rectangular提供的几何方法

6. Ordered Trait

package chapter12trait Ordered[T] {def compare(that: T): Intdef > (that: T) = compare(that) > 0def < (that: T) = compare(that) < 0def >= (that: T) = (this > that) || (this == that)def <= (that: T) = (this < that) || (this == that)
}class Rational(val n: Int, val d: Int) extends Ordered[Rational] {def compare(that: Rational) = this.n * that.d  - this.d * that.ndef equals(that: Rational) = (this.n * that.d - this.d * that.n) == 0
}object TestMain {def main(args: Array[String]) {val r1 = new Rational(3, 4)var r2 = new Rational(1, 2)println(r1 == r2)println(r1 > r2)println(r1 <= r2)}
}

客户代码只需实现compare和equals, > < >= <=由trait实现

trait中的this在这里就是动态绑定的,同理super也是

转载于:https://blog.51cto.com/dingbo/1589674

Programming in Scala (Second Edition) 读书笔记12 Trais相关推荐

  1. 《深入浅出图神经网络》读书笔记 1-2

    <深入浅出图神经网络>读书笔记 1-2 第1章 图的概述 第2章 神经网络基础 2.1 机器学习基本概念 2.2 神经网络 2.4 训练神经网络 第1章 图的概述 图神经网络(Graph ...

  2. Real-Time Rendering Fourth Edition读书笔记1

    Real-Time Rendering Fourth Edition读书笔记1:第一章-第四章 思维导图链接: 链接:https://pan.baidu.com/s/1ic8O_y2mHdoc68tE ...

  3. 《JavaScript高级程序设计》读书笔记 -12.1 window对象

    <JavaScript高级程序设计>读书笔记 -12.1 window对象 12.1 window对象 12.1.1 Global作用域 12.1.2 窗口关系[不是很懂] 12.1.3 ...

  4. The art of computer programming Donald E. Knuth volumn one third edition读书笔记1

    大名鼎鼎knuth的编程艺术,要读一读,特此写下读书笔记,引用网络红人留几手的话,我觉得我是一个艺术家,哈哈. 书的开头是讲读此书步骤,感觉Knuth萌萌哒: 1,请按以下步骤阅读,除非你已经开始读了 ...

  5. Practical Python and OpenCV 3rd Edition读书笔记_Chapter8_Smoothing and Blurring平滑与模糊_思维导图

    <Practical Python and OpenCV 3rd Edition>真的是一本非常棒的入门书籍. 它也很薄,只有166页,虽然是纯英文的,如果静下心来认真看一两天就可以读完. ...

  6. 《Programming in Lua 3》读书笔记(一)

    断断续续的看这本书快一个月了,由于平时要上班所以读书时间是零碎的,再加上直接看的是英文版,而自己的英语水平就那样,所以进度不咋样.快一个月了,300来页的电子版至今才看到40来页.当然一开始我也没做很 ...

  7. Programming in Scala 3rd edition中的一个问题

    2019独角兽企业重金招聘Python工程师标准>>> 第48页的例子中 thrill.sort((s,t)=>| s.charAt(0).toLower <| t.ch ...

  8. CLR via C# 读书笔记 1-2 创建线程的成本

    在clr中创建线程的代价还是比较高的 ,他需要两个部分 内存: 线程核心对象, 存放描述线程的一些内容和上下文 . (内存消耗:700B-2500B) 线程环境,存放例如异常处理链之类. (内存消耗 ...

  9. 《Programming in Lua 3》读书笔记(十二)

    日期:2014.7.14 PartⅡ Object-Oriented Programming Lua中实现面向对象编程. "如同OOP对象,table拥有状态:如同OOP对象,table拥有 ...

最新文章

  1. scikit正则化 API
  2. 一周一论文(翻译)——[PVLDB 17] Dhalion: 基于Heron自适应调整的流处理系统
  3. Linux Android 多点触摸协议 原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/os/71/12306571.shtml
  4. 就在刚刚!吴恩达的这门新课程终于开放注册了
  5. row_number() over (partition by....order by...)用法 分组排序
  6. linux的多任务 多进程,浅谈linux模拟多线程崩溃和多进程崩溃
  7. 考研c 语言程序设计题库,温州大学c语言程序设计考研复试核心题库(23页)-原创力文档...
  8. 杭电4500小Q系列故事——屌丝的逆袭
  9. xtragrid 某个值 查找_Java 经典算法:二分法查找(循环和递归两种方式实现)
  10. 强悍的 Vim —— .vimrc(vim 配置文件)
  11. C#写的ftp上传类
  12. C语言进制转换 10进制转16进制(一)
  13. jszip 解压压缩包_Node.js使用jszip实现打包zip压缩包
  14. html图片与文字的排版6,HTML文字与排版
  15. linux中shift用法,Linux shell脚本中shift的用法说明
  16. html bottom没有效果,css 设置margin-top或margin-bottom失效不取作用的解决方法
  17. 增大图像感受野方法的总结
  18. 魔法书《SICP》的简明介绍 - 为什么要学习SICP
  19. Java开发笔记(二)Java工程的帝国区划
  20. 申请苹果开发者账号(2016最新版)

热门文章

  1. exchange之2003迁移至2007
  2. excel去掉超链接
  3. Java_压缩与解压工具类
  4. React基础——快速搭建开发环境
  5. AGG第二十二课 conv_contour函数auto_detect_orientation的字体应用
  6. TOJ 3750: 二分查找
  7. Android 热修复总结
  8. 在某些情况下明明添加了引用,为何VS还报错XXX不存在类型或命名空间(是否缺少程序集引用)...
  9. input 的read only 和 disable的区别
  10. 更改centos 5 yum源