1. 程式人生 > >Scala 類型界定

Scala 類型界定

col log str nbsp demo 子類 類型 pan blog

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]
}

Scala 類型界定