上下文界定的类型参数形式为T:M的形式,其中M是一个泛型,这种形式要求存在一个M[T]类型的隐式值:
/** * 上下文界定 */ @Test def testOrdering_Class_Context() = { class User(val userName: String, val age: Int) class UserOrderingObject extends Ordering[User] { override def compare(x: User, y: User): Int = x.age - y.age } class Pair[T: Ordering](val first: T, val second: T) { def smaller(implicit ord: Ordering[T]) = { if (ord.compare(first, second) > 0) second else first } } val u1 = new User("u1", 12) val u2 = new User("u2", 13) //提供隐式值,隐式值需要提供在创建Pair之前 implicit val uo = new UserOrderingObject val p = new Pair(u1, u2) println(p.smaller.age) } /** * 上下文界定 */ @Test def testOrdering_Object_Context_1() = { class User(val userName: String, val age: Int) //TODO 隐式object伴生对象 implicit object UserOrderingObject extends Ordering[User] { override def compare(x: User, y: User): Int = x.age - y.age } class Pair[T: Ordering](val first: T, val second: T) { def smaller() = { //TODO 获取隐式对象 val ord = implicitly[Ordering[T]] if (ord.compare(first, second) > 0) second else first } } val u1 = new User("u1", 12) val u2 = new User("u2", 13) // 有隐式伴生对象不再需要提供隐式值 val p = new Pair(u1, u2) println(p.smaller.age) } /** * 上下文界定 */ @Test def testOrdering_Object_Context_2() = { class User(val userName: String, val age: Int) object UserOrderingObject extends Ordering[User] { override def compare(x: User, y: User): Int = x.age - y.age } class Pair[T: Ordering](val first: T, val second: T) { def smaller() = { val ord = implicitly[Ordering[T]] if (ord.compare(first, second) > 0) second else first } } val u1 = new User("u1", 12) val u2 = new User("u2", 13) implicit val uo = UserOrderingObject val p = new Pair(u1, u2) println(p.smaller.age) }
时间: 2024-10-12 19:22:19