0

Error while passing arguments to methods. I have an object builddeequ_rules and calling methods using Scala reflection.

  def build(rules: List[Map[String, Any]]): Check = {
    for (constraint <- rules) {
     val name = constraint("name")
     val args = constraint("args")
     val hiObj = builddeequ_rules
     val mtd = hiObj.getClass.getMethod(name.toString,args.getClass)
     mtd.invoke(hiObj,args)
    }



import com.amazon.deequ.checks.{Check, CheckLevel}

object builddeequ_rules {
   var checks = Check(CheckLevel.Warning, "Data unit test")

def isComplete(args: Any)  {
   val arg = args.asInstanceOf[Map[String,Any]]
   val columnName = arg("column").toString
  checks = checks.isComplete(columnName)
 }

def isUnique(args: Any)  {
   val arg = args.asInstanceOf[Map[String,Any]]
   val columnName = arg("column").toString
  checks = checks.isUnique(columnName)
 }
def isPositive(args: Any)  {
   val arg = args.asInstanceOf[Map[String,Any]]
   val columnName = arg("column").toString
  checks = checks.isPositive(columnName)
 }

I am getting below error. Need help!

Error: type mismatch;
found : Any
required: Object
mtd.invoke(hiObj,args)

Arvinth
  • 60
  • 6
  • 27

1 Answers1

3

java.lang.Object is more or less scala.AnyRef. scala.Any is (simplyfying) a superset of objects and primitives. So the compiler is warning you, that you are trying to pass something that could potentially be primitive (Any) as java.lang.Object.

On bytecode level Any will quite often be just Object, sure, but Scala's type system make the distinction between things that are "natively" Objects and things that could involve autoboxing to make them Objects, and that's the error you see.

So the solution here would be to have this object annotated as AnyRef or even better, as java.lang.Object to clearly show that you want to use it for something Java/JVM-specific.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
  • I annotated `args ` as `java.land.Object`, But now i am getting `java.lang.NoSuchMethodException: builddeequ_rules$.isComplete(scala.collection.immutable.Map$Map1)` error – Arvinth Jul 10 '20 at 00:46
  • I was able to solve the issue by referring this question https://stackoverflow.com/questions/53044552/java-lang-nosuchmethodexception-scala-collection-immutable-coloncolon. Used Scala reflection instead of Java reflection. – Arvinth Jul 10 '20 at 07:00