Donald
Donald

Reputation: 753

Scala convert ArrayList in Map[String, Any] to Seq

I'm trying to read in a .yaml file into my Scala code. Assume I have the following yaml file:

animals: ["dog", "cat"]

I am trying to read it using the following code:

val e = yaml.load(os.read("config.yaml")).asInstanceOf[java.util.Map[String, Any]]
val arr = e.getOrDefault("animals", new Java.util.ArrayList[String]()) // arr is Option[Any], but I know it contains java.util.ArrayList<String>
arr.asInstanceOf[Buffer[String]] // ArrayList cannot be cast to Buffer

The ArrayList is type Any, so how do I cast to a Scala Collection e.g. Buffer? (Or Seq, List...)

Upvotes: 0

Views: 617

Answers (2)

Tomer Shetah
Tomer Shetah

Reputation: 8529

Another option you have is to define the model of you configuration, for example:

class Sample {
  @BeanProperty var animals = new java.util.ArrayList[String]()
}

The following will create an instance of Sample:

val input = new StringReader("animals: [\"dog\", \"cat\"]")
val yaml = new Yaml(new Constructor(classOf[Sample]))
val sample = yaml.load(input).asInstanceOf[Sample]

Then, using CollectionConverters in Scala 2.13, or JavaConverters in Scala 2.12 or prior, convert animals into a Scala structure:

val buffer = sample.getAnimals.asScala

Code run at Scastie.

Upvotes: 0

tentacle
tentacle

Reputation: 553

SnakeYaml (assuming what you're using) can't give you a scala collection like Buffer directly.

But you can ask it for ArrayList of string and then convert it to whatever you need.

import scala.jdk.CollectionConverters._
val list = arr.asInstanceOf[util.ArrayList[String]].asScala

results in:

list: scala.collection.mutable.Buffer[String] = Buffer(dog, cat)

Upvotes: 1

Related Questions