Scala - Why the dot doesn't apply in this case
I am parsing XML and I am chaining calls without a dot. All of these methods take no parameters (other than \\
which takes one), so it's perfectly possible to link them without a dot, right?
This is the code that doesn't work:
val angle = filteredContextAttributes.head \\ "contextValue" text toDouble
Mistake: not found: value toDouble
However, it works like this:
(filteredContextAttributes.head \\ "contextValue" text) toDouble
text
returns only String
and takes no parameters, and I don't see any other parameters required in \\
order to cause the problem.
What am I missing? I don't want to hack it, but to understand what the problem is.
And also I cannot use head
without a dot. When deleting a point, it says:Cannot resolve symbol head
source to share
This is because text
- it is postfix - it means the method follows the object and does not take any parameters. The trick with postfix is ββthat it can only appear in the end statement . So when you add parentheses, it works (the expression is then bracketed and you end up with two postfix notations, one ends with text and the other ends with toDouble ). In your example, this is not how you are trying to call a method further down the chain.
This is also the reason why you need to do filteredContextAttributes.head
instead filteredContextAttributes head
. I'm sure if you do it (filteredContextAttributes head)
, it will work as soon as the postfix notation is at the end of the expression!
There are prefix and infix notations in Scala , and I highly recommend you read about them to find out when you can skip over .
and ()
(like why you need to ()
when using a method map
, etc.).
source to share
To add, as @Mateusz already answered, it has to do with mixing postfix notation and arity-0 suffix notation .
There's also a great post in another answer: fooobar.com/questions/430486 / ...
You can even see a warning in your shorter example:
scala> filteredContextAttributes.head \\ "contextValue" text
<console>:10: warning: postfix operator text should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
This is a rather subtle hint that this is not the best style for style. So, unless you are specifically working in DSL, you should prefer to add explicit periods and parentheses, especially when mixing infix, postfix and / or suffix notes.
For example, you might prefer doc \\ "child"
over doc.\\("child")
, but once you step outside the DSL - in this example, when you get NodeSeq
yours, prefer to add to perens.
source to share