这篇文章是参考其他博客,并加了一些自己的理解和注释
源博客地址:https://www.iteblog.com/archives/1325.html
scala中Trait基本介绍
XML Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
package com.lyzx.day02/ ** * Created by MECHREVO on 2017/ 12/ 8. */ class T1(_year:Int,_month:Int,_day:Int) extends Order{ def year = _year; def month = _month; def day = _day; override def toString()= "year[" +year+"] month[" +month+"] day[" +day+"]" def < (that:Any):Boolean ={ if(!that.isInstanceOf[T1]) sys.error("error" ); val o = that.asInstanceOf[T1]; (this.year< o.year) || (this.year == o.year && this.month < o.month )|| (this.year == o.year && this.month == o.year && this.day == o.day) } override def equals(that:Any):Boolean={ that.isInstanceOf[T1] && { val o = that.asInstanceOf[T1] return o.year == this.year && o.month == this.month && o.day == this.day; } } }/ ** * 除了从父类集成代码外,Scala中的类还允许从一个或者多个traits中导入代码。 * * 对于Java程序员来说理解traits的最好方法就是把他们当作可以包含代码的接口(interface)。 * 其实它更像抽象类 * 在Scala中,当一个类继承一个trait时,它就实现了这个trait的接口, * 同时还从这个trait中继承了所有的代码。 */ trait Order{ def < (that:Any):Boolean def < = (that:Any):Boolean = this ==that || this == that def > (that:Any):Boolean = !(this < = that) } object T1{ def main(args: Array[String]) { val t1 = new T1(2017,10,29); val t2 = new T1(2017,10,29); print(t1.equals(t2)) } }
scala中泛型介绍
XML Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package com.lyzx.day02/ ** *scala中的泛型 */ // T和java中的一个含义 class T2[T] { private var v: T = _ def set(_v : T ): Unit ={ this.v = _v } def get(): T ={ v } } object T2{ def main(args: Array[String]) { val t = new T2[Int]() t.set(123) print(t.get()+321) } }
XML Code