0

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...)

1

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.