Goldengirl
Goldengirl

Reputation: 967

How to use flatMap in scala in order to group a set of "vals"

I am new to scala and was just creatting a few examples to understand it better. I can't seem to figure out this issue here- I create a List of Strings in my java program and use this list in my scala program. My scala code to read the list from the java class looks something like this.

  private val stringList : Seq[List] = x.getStringName //gets the list from my java program. 

The stringList contains

   ["How", "Are", "You"]. 

I am trying to find a way to add these strings to values called a, b and c, so that they could be later passed on a arguments to another function.

 val values = stringList.flatMap{
   case x if (!stringList.isEmpty) =>

      val a = /*should get the first string How*/
      val b = /*should get the second string Are*/
      val c = /*should get the third string You*/

  case _ => None
 }

 getCompleteString(a,b,c);

But this does not work. I tgives me an error saying

 "type mismatch; found : Unit required: scala.collection.GenTraversableOnce[?]"

I am not use why this happens. Could somebody tell me what am I doing wrong here?

I am sorry if the code looks dirty, but I am a beginner and still trying to understand the language. Any help is appreciated. Thank you in advance.

Upvotes: 1

Views: 430

Answers (1)

insan-e
insan-e

Reputation: 3921

There are many ways to do it:

val a = stringList(0)
val b = stringList(1)
val c = stringList(2)

val (a, b, c) = stringList match {
  case first :: second :: third :: _ => (first, second, third)
  case _ => ("default for a", "default for b", "default for c") // default case..
}

The first approach is Java-ish, by index, but you have to check if the elements are there, e.g. not-null or whatever.

The second one is using tuples, where you assign multiple values at once. If the list has at least 3 elements(first case statement), then they will be assigned to (a,b,c) tuple, and then you can use a,b,c... If the list has less than 3 elements, default values will be used(0,0,0).

I am sure that there are more ways to achieve this in Scala.

Upvotes: 1

Related Questions