Scala - ambiguous reference to overloaded definition — with varargs [duplicate]

会有一股神秘感。 提交于 2019-12-06 19:09:43

问题


Possible Duplicate:
How do I disambiguate in Scala between methods with vararg and without

I am currently porting part of an application to scala and it uses the Oval library. The method is question is the Validator.validate method. It has two signatures:

List<ConstraintViolation> validate(Object validatedObject)
List<ConstraintViolation> validate(Object validatedObject, String... profiles) 

The scala code looks generally like this:

def validate(toValidate: AnyRef) = {
  val validator = createValidator
  validator.validate(toValidate)
}

And the error message:

error: ambiguous reference to overloaded definition,
[INFO] both method validate in class Validator of type (x$1: Any,x$2: <repeated...>[java.lang.String])java.util.List[net.sf.oval.ConstraintViolation]
[INFO] and  method validate in class Validator of type (x$1: Any)java.util.List[net.sf.oval.ConstraintViolation]
[INFO] match argument types (AnyRef)
[INFO]       this.validator.validate(toValidate)

How can I get this be be unambiguous?


回答1:


I think that this could be a duplicate of How do I disambiguate in Scala between methods with vararg and without

Basically, it is a known java-scala-interop problem, and the only workarounds involve extra Java adapters to make accessible in Scala.




回答2:


The only way I know of is to use reflection:

val ambiguous = validator.getClass.getMethods.filter(_.getName == "validate")
val wanted = ambiguous.find(_.getParameterTypes.length == 1).get
wanted.invoke(validator, toValidate).asInstanceOf[java.util.List[ConstraintViolation]]


来源:https://stackoverflow.com/questions/6209120/scala-ambiguous-reference-to-overloaded-definition-with-varargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!