我有一个Scala类,它使用Apache Spark中的MR作业返回输入类型IN的最大值。如果我从Scala调用它,这个类工作正常,它的工作原理如下:
// Class
class TypedMax[IN, T](val f: IN => T)(implicit ev$1: T => Ordered[T], ev$2: TypeTag[T])
extends Aggregator[IN, T, T] {
override def zero: T = null.asInstanceOf[T]
override def reduce(b: T, a: IN): T = if (b > f(a)) b else f(a)
override def merge(b1: T, b2: T): T = if (b1 > b2) b1 else b2
override def finish(reduction: T): T = reduction
}
// Call function
def max[IN, T](f: IN => T)(implicit ev$1: T => Ordered[T], ev$2: TypeTag[T]): TypedColumn[IN, T] =
new TypedMax[IN, T](f).toColumn
现在我想让它也可以从java调用,但是我在传递隐式参数时遇到了一些困难。我知道隐式参数可以通过将它们附加到Java中的参数列表来传递,但隐式参数在Scala中。因此,我正在尝试执行以下操作:
class TypedMax[IN, T](val f: IN => T)(implicit ev$1: T => Ordered[T], ev$2: TypeTag[T])
extends Aggregator[IN, T, T] {
override def zero: T = null.asInstanceOf[T]
override def reduce(b: T, a: IN): T = if (b > f(a)) b else f(a)
override def merge(b1: T, b2: T): T = if (b1 > b2) b1 else b2
override def finish(reduction: T): T = reduction
// Java api support
def this(f: MapFunction[IN, java.lang.Double]) =
this(x => f.call(x).asInstanceOf[T])(ev$1: T => Ordered[T], ev$2: TypeTag[T])
然后可以从java调用:
public static <T> TypedColumn<T, Double> max(MapFunction<T, Double> f) {
return new TypedMax<T, Double>(f).toColumn();
}
我已尝试使用implicity
implicit
并使用逗号和括号来传递来自辅助构造函数的含义的许多排列。然而,它总是抱怨没有找到ev $ 1和ev $ 2。我必须传递参数,否则会出错:
Error:(135, 5) No implicit view available from T => Ordered[T].
this(x => f.call(x).asInstanceOf[T])
Error:(135, 5) not enough arguments for constructor TypedMax: (implicit ev$1: T => Ordered[T], implicit ev$2: reflect.runtime.universe.TypeTag[T])org.apache.spark.sql.execution.aggregate.TypedMax[IN,T].
Unspecified value parameters ev$1, ev$2.
this(x => f.call(x).asInstanceOf[T])
如果我尝试:
def this(f: MapFunction[IN, T]) =
this(x => f.call(x))(T => Ordered[T], TypeTag[T])
结果是:
Error:(135, 38) value Ordered of type scala.math.Ordered.type does not take type parameters.
this(x => f.call(x))(T => Ordered[T], TypeTag[T])
Error:(135, 50) missing argument list for method apply in object TypeTag
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `apply _` or `apply(_,_)` instead of `apply`.
this(x => f.call(x))(T => Ordered[T], TypeTag[T])
我错过了什么/误会? 谢谢!
答案 0 :(得分:1)
T => Ordered[T]
并不代表您认为的含义,而是创建一个带有参数Function1
和正文T
的{{1}}。请尝试以下方法:
scala.math.Ordered.apply[T]
(我不确定你是否能够从java中实现def this(f: MapFunction[IN, T], e: MapFunction[T, Ordered[T]], tt: TypeTag[T]) =
this(x => f.call(x))(x => e.call(x), tt)