目录
- 概述
- 实践
- 代码
- 执行
- 结束
概述
scala泛型结合隐式转换使用
实践
代码
package com.fun.scala
/**
* 视图界定
*/
object Genericity04 {
def main(args: Array[String]): Unit = {
val s1 = new Stu("test", 33)
val s2 = new Stu("test2", 32)
println(new MaxValue2(s1, s2).compare)
// 隐式转换与泛型结合
implicit def stu2Ordered(stu: Stu2) = new Ordered[Stu2] {
override def compare(that: Stu2): Int = stu.age - that.age
}
val s3 = new Stu2("test", 33)
val s4 = new Stu2("test2", 34)
println(new MaxValue2(s3, s4).compare)
}
// <% 视图界定 int2Integer
class MaxValue2[T <% Comparable[T]](a: T, b: T) {
def compare = if (a.compareTo(b) > 0) a else b
}
// Ordered 使用的是 Comparable
class MaxValueOrdered[T <% Ordered[T]](a: T, b: T) {
def compare = if (a.compareTo(b) > 0) a else b
}
}
class Stu(val name: String, val age: Int) extends Ordered[Stu] {
override def compare(that: Stu): Int = this.age - that.age
override def toString: String = this.name + "\t" + this.age
}
class Stu2(val name: String, val age: Int) {
override def toString: String = this.name + "\t" + this.age
}
执行
结束
scala泛型结合隐式转换使用
至此结束。