Is it possible to create object without declaring class?
Is it possible to create object without declaring class? Like in JavaScript
obj = {a: '1'}; console.log(obj.a)
In Groovy you must always provide the class of an object being created, so there is no equivalent in Groovy to JavaScript's object-literal syntax.
However, Groovy does have a literal syntax for a Map
, which is conceptually very similar to a JavaScript object, i.e. both are a collection of properties or name-value pairs.
The equivalent Groovy code to the JavaScript above is:
def obj = [a: '1']
println obj.a
Even though there is no class name used here you're still creating an object of a particular class (java.util.LinkedHashMap
). The code above is just shorthand for:
def obj = new LinkedHashMap();
obj.a = '1'
println obj.a
The Expando
class is perhaps even more similar to a JavaScript object, and is useful when you want to avoid the "overhead" of defining a class, or want a dynamic object to which any arbitrary property can be added at runtime.
Slightly surprised that nobody has mentioned the Expando class. This adds extra functionality over a map in that you can directly reference properties within your functions. Code example below.
def expando = new Expando(a:"def")
expando.run = {def b ->
println("$a")
println("$b")
}
expando.run("ABC")
def map = [a:"def"]
map.run = {def b ->
println("$a") //THIS DOES NOT WORK. You will get a missing property exception.
println("$b")
}
map.run("ABC")
printed output:
def
ABC
groovy.lang.MissingPropertyException
ABC (if you comment out the println($a) in the map.run, println($b) prints out ABC)
Ignore the extra line breaks in the output. Was having a heck of a time putting def and ABC on consecutive lines.
See the Expando API documentation for more information.
Groovy has an equivalent notation for json. Only difference is they use [:] for maps instead of {}. So you can clearly convert a json into a groovy object notation.
import groovy.json.JsonOutput
def obj = [:] //define map
obj.batsmen = [] //define array
def b = [:]
b.name= "V. Kohli"
b.score = 55
b.strike = false
obj.batsmen.push(b)
//push second object
obj.batsmen.push(b)
println JsonOutput.toJson(obj)
Here I have not printed the object directly. Since it will print with square braces notation.
Read the whole article. Groovy for javascript developers. https://metamug.com/article/groovy-for-javascript-developers.php
You can use a literal map:
config = [
host : '0.0.0.0',
user : 'user1',
password: 'pass'
]
println("""
HOST: ${config.host}
USER: ${config.user}
PASS: ${config.password}
""")
You can also return a literal map as a function return value without having to define a custom class e.g.
return [status: 200, body: 'abcdef']
and then in the caller access the values e.g. withresponse.status
.