class User(val userName: String,val age: Int) extends Comparable[User] { override def compareTo(o: User): Int = this.age - o.age } object OrderingDemo extends App { /** * 类型界定,上界 * * @param u1 * @param u2 * @tparam T T必须是Comparable[T]的子类 * @return */ def compare[T <: Comparable[T]](u1: T, u2: T): Int = { if (u1.compareTo(u2) == 0) 0 else if (u1.compareTo(u2) > 0) 1 else -1 } val u1 = new User("u1", 18) val u2 = new User("u2", 19) // compare(u1,u2) //class User(userName: String, age: Int)的话,编译不通过 println(compare(u1,u2)) //class User(val userName: String,val age: Int) extends Comparable[User] }