Is it possible to create object without declaring class? Like in JavaScript
obj = {a: '1'}; console.log(obj.a)
Is it possible to create object without declaring class? Like in JavaScript obj =
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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:The
Expandoclass 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.