E0041

E0041#

Closed map pattern.

MoonBit's map pattern syntax does not support closed pattern (i.e. asserting that the map does not contain any other unmatched elements). So map patterns must always contain a .., otherwise this warning will be reported.

Erroneous example#

fn f(map : Map[String, Int]) -> Unit {
  match map {
    // the pattern still matches if `map` contain elements other than "x" and "y"
    { "x": x, "y": y } => println(x + y)
    _ => ()
  }
}

test {
 f({ "x": 1, "y": 2, "z": 3 })
}

Suggestion#

  • If the intended semantic is open matching (i.e. allow existence of unmatched elements), just add .. to the map pattern.

  • If the intended semantic is closed matching, use pattern guard instead:

    fn f(map : Map[String, Int]) -> Unit {
      match map {
        { "x": x, "y": y, .. } if map.size() == 2 => println(x + y)
        _ => ()
      }
    }