vendredi 9 avril 2021

Scala Map pattern matching issue

I am new to Scala,

For every key in a map, I want to match a new value

class SomeLongNameObject {
    val m: Map[String, String] = Map("a" -> "aa",
      "b" -> "bb",
      "other" -> "someString")

    m.map {
      case (aKey, v) => println("a found")
      case (bKey, v) => println("b found")
      case (k,v) => println("fallback")
    }
  }

  object SomeLongNameObject {
    val aKey = "a"
    val bKey = "b"
  }
  val someObject = new SomeLongNameObject

I expect (and desire) that the given map will print

a found

b found

fallback

however, the result is

a found

a found

a found

As I understand the aKey from the SomeLongNameObject object not used in the case (aKey, v), Is there a way to force it to use the vals from the object SomeLongNameObject in a more elegant way than below?

m.map {
      case (SomeLongNameObject.aKey, v) => println("a found")
      case (SomeLongNameObject.bKey, v) => println("b found")
      case (k,v) => println("fallback")
    }

Aucun commentaire:

Enregistrer un commentaire