3

After using Scala for a while and reading about all over the place and especially here

I was sure I know when to use curlies. as a rule of thumb if I want to pass a block of code to be executed i will use curly braces.

how ever this nasty bug surfaced using elastic4s DSL using curly braces:

bool {
  should {
    matchQuery("title", title)
  }
  must {
    termQuery("tags", category)
  }
}

compiles to:

{
  "bool" : {
    "must" : {
      "term" : {
        "tags" : "tech"
      }
    }
  }
}

while using parenthesis:

bool {
       should (
         matchQuery("title", title)
        ) must (
         termQuery("tags", category)
        )
      }

gives the correct result:

{
  "bool" : {
    "must" : {
      "term" : {
        "tags" : "tech"
      }
    },
    "should" : {
      "match" : {
        "title" : {
          "query" : "fake",
          "type" : "boolean"
        }
      }
    }
  }
}

This was compiled using scala 2.11.6 - Even more confusing is that evaluating the expression in intellij debugger gives correct result no matter what I am using.

I noticed only the last expression was being evaluated why is that?

raam86
  • 6,785
  • 2
  • 31
  • 46

1 Answers1

8

Probably problem not in braces, but in infix notation. Look at lines

  should {
    matchQuery("title", title)
  }
  must {

must goes next line, so it is interpreted as new expression but not as continuation of should. You probably must place it on the same line with closing brace

  should {
    matchQuery("title", title)
  } must {
Odomontois
  • 15,918
  • 2
  • 36
  • 71
  • Great answer. Also explains why it works in the intellij debugger – raam86 Apr 26 '15 at 14:53
  • 1
    The bool construct is the most annoying one to use, I'd be open to suggestions on how to make it clearer. Also, another gotcha is using sequences with {}, if you have a method that takes multiple params, say `bulk` then you must use () or create a Seq yourself. – sksamuel Apr 26 '15 at 19:03