与view bounds一样context bounds(上下文界定)也是隐式参数的语法糖
我们使用view bounds的方式的写法如下:
class Pairs[T <% Comparable[T]](first: T,second:T){ def bigger ={ if (first.compareTo(second)>=0) first else second } }
如果我们利用隐式转换,可以改成如下写法
class Pairs_implicit[T](first: T,second:T){ def bigger(implicit ordered: Ordering[T]) ={ if (ordered.compare(first, second)>0) first else second } }
Scala提供了Context Bounds方法,写法如下:
class Pairs_Context_Bounds[T: Ordering](first: T,second:T){ def bigger(implicit ordered: Ordering[T]) ={ if (ordered.compare(first, second)>0) first else second } }
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/194602.html