I'm going to start the comparison of string handling in Scala and Groovy with a look at single line strings - the sort of string found in Java.
String s = "Hello, Java!";
Scala's basic string handling is just like Java (but with Scala's syntax and type inference):
var s: String = "Hello, Scala!"
var s2 = "Hello Type Inferer!"
Groovy has both Java-esque strings that are enclosed in double quotes as well as strings that are enclosed in single quotes.
def s = "Groovy's double quoted String"
def s2 = 'A "single quoted" Groovy String'
Groovy also has a third syntax for strings, using forward slashes
def s3 = /Slashy String/
All of the above are java.lang.String - however in Groovy, double quoted strings can become "GStrings". GStrings contain an expression contained in a ${ } block (something that will be familiar to anyone who has written JSP pages). For example:
def x = 4
def gs = "the value of x is: ${x}"
println gs
will print:
the value of x is: 4
Double quoted strings only get promoted to GStrings when they contain ${some expression}. If they don't, then they're plain old java.lang.String strings.
Multi-line Strings
Both Scala and Groovy support multi-line strings. Both use a similar syntax - the triple quote:
var ms = """This is
a Scala multi-line
String"""
def ms = """This is
a Groovy ${lines}
String"""
You'll notice that in Groovy, multi-line strings get promoted to GStrings as well.
Character
While looking at Strings, we should also look at Character. In a manner not dissimilar to Java, a Character in Scala is defined by a single character in single quotes:
val c = 'd'
In Groovy, Characters can't be created directly. This:
def c = 'd'
creates a String, not a Character. Instead, you need to write this:
def c = 'd' as char
which will create a String and then use some dynamic magic to convert it to a Character
End of Part 1
That's it for the basic comparison. However, both languages have syntactic sugar that gets layered onto strings, but that really should be a post on it's own.
0 comments:
Post a Comment