Real difference between curly braces and braces in scala

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

I was pretty sure I knew when to use curls. generally, if I want to pass a block of code to execute, I will use curly braces.

lest this nasty error pop up when using elastic DSLs using curly braces:

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

      

will compile:

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

      

when using brackets:

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 the intellij debugger gives the correct result no matter what I use.

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

+3


source to share


1 answer


The problem is probably not curly braces, but infix notation. Look at the lines

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

      



must

goes on the next line, so it is interpreted as a new expression, but not as a continuation should

. You should probably place it in line with the closing brace

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

      

+8


source







All Articles