在以下示例中,我使用的是view bound
和upper bound
。代码完全相同,只是<%
和<:
的符号不同。 view bound
和upper bound
之间有什么区别?
scala> class Person[T <% Ordered[T]](val fn:T, val ln:T) {
| def greater = if (fn > ln) fn else ln
| }
defined class Person
scala> val p1 = new Person("manu", "chadha")
p1: Person[String] = Person@31b91435
scala> val p2 = new Person("anita", "chadha")
p2: Person[String] = Person@61e0f9b9
scala> p1.greater
res3: String = manu
scala> p2.greater
res4: String = chadha
scala> class Person2[T <: Ordered[T]](val fn:T, val ln:T) {
| def greater = if (fn > ln) fn else ln
| }
defined class Person2
scala> val p3 = new Person("manu", "chadha")
p3: Person[String] = Person@7c50709a
scala> val p4 = new Person("anita", "chadha")
p4: Person[String] = Person@1d686622
scala> p3.greater
res5: String = manu
scala> p4.greater
res6: String = chadha
scala>