/**
* "<%" 视图界定, 背后有隐式转换,如将Int变成了RichInt
* @param first
* @param second
* @param ev$1
* @tparam T
*/
class Pair_NotPerfect[T <% Comparable[T]](val first: T, val second: T) {
def bigger = if(first.compareTo(second) > 0) first else second
}
//这种写法更好
class Pair_Better[T <% Ordered[T]](val first: T, val second: T) {
def bigger = if(first > second) first else second
}
object View_Bounds {
def main(args: Array[String]): Unit = {
val pair = new Pair_NotPerfect("Spark", "Hadoop")
println(pair.bigger)
val pairInt = new Pair_NotPerfect(3, 5) // Int -> RichInt
println(pairInt.bigger)
val pair_better_string = new Pair_Better("Java", "Scala") //String -> RichString
println(pair_better_string.bigger)
val pair_better_int = new Pair_Better(20, 30)
println(pair_better_int.bigger)
}
}
scala进阶3-视图界定view bounds
最新推荐文章于 2020-08-29 21:46:30 发布