Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 对同一类型使用不同的隐式值_Scala_Apache Spark - Fatal编程技术网

Scala 对同一类型使用不同的隐式值

Scala 对同一类型使用不同的隐式值,scala,apache-spark,Scala,Apache Spark,我需要调用一个库的排序方法,该方法采用隐式排序参数,方法如下: class OrderedRDDFunctions[K : Ordering : ClassTag, V: ClassTag] (self: RDD[P]) { private val ordering = implicitly[Ordering[K]] def sort() = { // uses ordering value } } 现在,我需要在一个

我需要调用一个库的排序方法,该方法采用隐式
排序
参数,方法如下:

class OrderedRDDFunctions[K : Ordering : ClassTag,
                          V: ClassTag] (self: RDD[P]) {

  private val ordering = implicitly[Ordering[K]]

  def sort() = {
    // uses ordering value
  }
}
现在,我需要在一个循环中调用此函数两次,使用相同类型的不同
顺序,如下所示

var A: RDD[(Int, Int, Int)] = ...
var C: RDD[(Int, Int, Int)] = ...

while(...) {

    implicit val ijOrdering:Ordering[(Int, Int, Int)] = new Ordering[(Int, Int, Int)] {
      override def compare(a: (Int, Int, Int), b: (Int, Int, Int)) = {
        val c = a._1.compare(b._1)
        if(c != 0) c
        else a._2.compare(b._2)
      }
    }
    A.sort() // should use ijOrdering above

    implicit val kjOrdering:Ordering[(Int, Int, Int)] = new Ordering[(Int, Int, Int)] {
      override def compare(a: (Int, Int, Int), b: (Int, Int, Int)) = {
        val c = a._3.compare(b._3)
        if(c != 0) c
        else a._2.compare(b._2)
      }
    }
    C.sort() // should use kjOrdering above

}

sort()方法中使用两个不同的隐式排序实例。但这给了我一个编译错误。如何在此设置中声明不同的隐式排序?请注意,我无法更改库方法

您可以使用块来限制隐式的范围。一个简单的例子:

object Blocks extends App {
  def meth()(implicit e: Int) = e * 2

  locally {
    implicit val k = 21
    println(meth()) // finds k and prints 42
  }

  locally {
    implicit val j = 11
    println(meth()) // finds j and prints 22
  }
}
如果块外存在冲突隐式,则此操作无效

请注意,
本地{..stmts..}
通常等同于
{..stmts..}
,但出于可读性考虑,我更喜欢它。你可以阅读更多关于那是什么的内容