第45讲:Scala中Context Bounds代码实战及其在Spark中的应用源码解析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第45讲:Scala中Context Bounds代码实战及其在Spark中的应用源码解析相关的知识,希望对你有一定的参考价值。

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


本文出自 “叮咚” 博客,请务必保留此出处http://lqding.blog.51cto.com/9123978/1742167

以上是关于第45讲:Scala中Context Bounds代码实战及其在Spark中的应用源码解析的主要内容,如果未能解决你的问题,请参考以下文章