In Groovy, the below produces the error message seen, just like Java would (apart from the different quotes and missing semicolon)
assert false : 'If you see me, colons are allowed!'
This also products the error message, but a comma is separating the message from the Boolean expression
assert false, 'If you see me, commas are allowed!'
I can't find anything about this in the Groovy documentation, is this correct behavior?
You can try this on the Groovy web console.
I'm not asking if it does allow commas, clearly it seems to, but I'm wondering if I have missed something in the documentation, this is a bug, or if it's just undocumented.
Both are valid, as you can see in the antlr grammar file for Groovy
| "assert"! assertAle: assignmentLessExpression!
( options {greedy=true;} :
( COMMA! nls! // TODO: gratuitous change caused failures
| COLON! nls! // standard Java syntax, but looks funny in Groovy
)
assertE:expression[0]!
)?
The comma syntax seems to have been added because the colon syntax (of Java) looks funny in Groovy.
Related
I'm curious about the eslint warning "no-useless-concat".
From other stackoverflow questions I saw using template-literals is the preferred method of concatenating strings dynamically, in order to not get such eslint warnings.
I want to define a css-class based upon a condition (liked is a boolean):
const heartClass = `fa fa-heart${liked ? "" : "-o"}`;
While compiling (using React) I still get the following warning:
WARNING in src\components\Like.jsx
Line 6:55: Unexpected string concatenation of literals no-useless-concat
What am I doing wrong - Why do I still get the no-useless-concat warning?
Kind Regards
Andreas
I found this in Groovy Syntax documentation at 4.6.1. Special cases:
As slashy strings were mostly designed to make regexp easier so a few
things that are errors in GStrings like $() or $5 will work with
slashy strings.
What $() syntax means? give some usage examples please
I also found it at Define the Contract Locally in the Repository of the Fraud Detection Service:
body([ // (4)
"client.id": $(regex('[0-9]{10}')),
loanAmount : 99999
])
but I don't understand what $() means when used with regex('[0-9]{10}').
It means nothing (or what you make of it). There are two places, you
are addressing, but they have nothing to do with each other.
The docs just mention this as "you can use slashy strings to write
things, that would give you an error with a GString" - the same is true
for just using '-Strings.
E.g.
"hello $()"
Gives this error:
unknown recognition error type: groovyjarjarantlr4.v4.runtime.LexerNoViableAltException
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/tmp/x.groovy: 1: token recognition error at: '(' # line 1, column 9.
"hello $()"
The parser either wants a { or any char, that is a valid first char
for a variable (neither ( nor 5 is).
The other place you encountered $() (in Spring cloud contract), this
is just a function with the name $.
Form the docs 8. Contract DSL:
You can set the properties inside the body either with the value method or, if you use the Groovy map notation, with $()
So this is just a function, with a very short name.
E.g. you can try this yourself:
void $(x) { println x }
$("Hello")
I try to create a small DSL, but i'm struggling with even simple stuff.
The following script gives me an error.
def DEMON(String input) {
['a': input]
}
DEMON 'Hello thingy' a
For some reasons, the parentheses around the parameters are not optional and i get an error.
This script runs fine:
def dEMON(String input) {
['a': input]
}
dEMON 'Hello thingy' a
Note: the only difference is the lowercase first char.
So what is going on here? Why are the scripts interpreted (compiled?) different? Is there some kind of method/class naming schemes i have to follow?
Update: The error message. I guess a Syntax error:
unexpected token: Hello thingy # line 4, column 7.
The groovy syntax is sometime complex, and the compiler use some rules to choose what it must do. One of this rule is simple : If a word starts with an uppercase, it's probably a class.
for example, f String is a syntax valid in groovy, and the compiler converts it to f(String.class).
you can use parenthesis to help groovy understand your DEMON is not a class but a method, DEMON('Hello thingy', a)
I'm getting a garbled JSON string from a HTTP request, so I'm looking for a temp solution to select the JSON string only.
The request.params() returns this:
[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,
callback=jQuery1707229194729661704_1329793018352
I would like everything from the start of the '{' to the end of the '}'.
I found lots of examples of doing similar things with other languages, but the purpose of this is not to only solve the problem, but also to learn Scala. Will someone please show me how to select that {....} part?
Regexps should do the trick:
"\\{.*\\}".r.findFirstIn("your json string here")
As Jens said, a regular expression usually suffices for this. However, the syntax is a bit different:
"""\{.*\}""".r
creates an object of scala.util.matching.Regex, which provides the typical query methods you may want to do on a regular expression.
In your case, you are simply interested in the first occurrence in a sequence, which is done via findFirstIn:
scala> """\{.*\}""".r.findFirstIn("""[{"insured_initials":"Tt","insured_surname":"Test"}=, _=1329793147757,callback=jQuery1707229194729661704_1329793018352""")
res1: Option[String] = Some({"insured_initials":"Tt","insured_surname":"Test"})
Note that it returns on Option type, which you can easily use in a match to find out if the regexp was found successfully or not.
Edit: A final point to watch out for is that the regular expressions normally do not match over linebreaks, so if your JSON is not fully contained in the first line, you may want to think about eliminating the linebreaks first.
What is the standard (or best practice) for Groovy error messages that that shouldn't span over a certain number of characters/line, e.g., 80 characters?
Consider the following (which is working fine)
throw new IOException("""\
A Jenkins configuration for the given version control
system (${vcs.name}) does not exist."""
.stripIndent()
.replaceAll('\n', ' '))
This will result in a one-line error message with no indention characters (what I want). But is there some other way ("the Groovy way of doing it") how to achieve this? If not, how could you add such a method to the GString class in a standalone Groovy application (if found hints regarding a Bootstrap.groovy file but it seems to be related to Grails)?
Example: """Consider a multi line string as shown above""".toSingleLine()
You could use the String continuation character then strip multiple spaces:
throw new IOException( "A Jenkins configuration for the given version control \
system (${vcs.name}) does not exist.".replaceAll( /( )\1+/, '$1' ) )
Or you could wrap this in a function and add it to the String.metaClass as I believe the answers you've seen point to.
You're right in thinking that Bootstrap.groovy is a Grails thing, but if you just set the metaClass early on in your applications lifecycle, you should get the same result...
String.metaClass.stripRepeatedWhitespace = { delegate.replaceAll( /( )\1+/, '$1' ) }
In saying all this however, I'd probably just keep the message on a single line