algui91 algui91 - 3 months ago 9
Scala Question

Populate a Vector in Scala

I am new with

Scala
.

I have a
Vector
in a class called
Sentence
:

val tree: Option[Vector[Node]]


The constructor of this class receives an
Array[String]
of words. For each word, I have to create a
Node
object (A class I've created), and then populate the
Vector
with all the nodes.

I am trying to fill the
tree
, but I am having problems writing the code. I have tried using:

private val tree: Option[Vector[Node]] =
words.foreach(w => new Node(w, 9, "d", 0))

private val tree: Option[Vector[Node]] =
words.foreach(w => tree :: new Node(w, 9, "d", 0))


I've also tried with
map
, but it does not work.

How could I, for each word, create a
Node
and add it to the
Vector
?

NOTE: If you need more code, tell me and I update the question.

Answer

Simply:

// map each word to a Node
val tree: Array[Node] = words.map(w => new Node(w, 9, "d", 0))

If you want a Vector:

val treeVector: Vector[Node] = tree.toVector

The Option does not bring much since it is equivalent to an emty Vector.

Comments