0

i am using elasticsearch rest api search code which gives the search response here is how i was doing earlier

if (hitmap.containsKey("UserList")) {
      hitmap.get("UserList") match {
        case list:java.util.ArrayList[String] => val userlist = list.asScala
          userList.clear()
          for (number <- userlist) {
            userList += number
          }
      }
    }

everything works fine outputs is as expected but sbt shows a warning message

non-variable type argument String in type pattern java.util.ArrayList[String] is unchecked since it is eliminated by erasure
[warn]         case list:java.util.ArrayList[String] => val userlist = list.asScala
[warn]                             ^

after doing some research i found a way to resolve it with ClassTag while taking help from here How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

my code becomes

import scala.reflect.{ClassTag, classTag}

def matchList2[A : ClassTag](list: java.util.ArrayList[A]) = list match {
      case strlist: java.util.ArrayList[String @unchecked] if classTag[A] == classTag[String] => println("A List of strings!")
    }

now here the problem arises how can i convert hitmap.get("UserList") (which returns object here) to java.util.ArrayList[String] without using asInstanceOfto pass a parameter to matchList2 function also i cannot use pattern match so what would be the best solution over here

swaheed
  • 3,671
  • 10
  • 42
  • 103
  • What is the return type of `hitmap.get("UserList")`? And do you control it or it is a third party library? – Luis Miguel Mejía Suárez Dec 20 '19 at 14:24
  • its a third party library hitmap.get("UserList") returns an object – swaheed Dec 20 '19 at 14:26
  • 1
    The thing is that due erasure there is no way to tell at runtime if effectively that is an `ArrayList[String]` just `ArrayList`. So, the best you can do, if you want to avoid an `asInstanceOf` unsafe cast, would be something like `case list: java.util.ArrayList[_] => val userlist = list.asScala.iterator.map(_.toString).toList` – Luis Miguel Mejía Suárez Dec 20 '19 at 14:29
  • thanks the warning message does disappear....will that be the right practice now? – swaheed Dec 20 '19 at 14:40
  • 1
    A best practice would be to never have this kind of situations, but when interacting with third party services you do not have too much option. At least calling `_.toString` is guaranteed to return a **String**, but not necessary the String you wanted. – Luis Miguel Mejía Suárez Dec 20 '19 at 14:42

0 Answers0