3 ms·
In type-checked languages, object literals are fairly obtuse because an object literal is an anonymous class with only one instantiation point. For example, sup
by bjourne 9y ago
In type-checked languages, object literals are fairly obtuse because an object literal is an anonymous class with only one instantiation point. For example, suppose you have syntax to create an anonymous class like this:
{ x: 123, y: 456, z: 789 }
What type would it have and what would you do with it? The only use for it would be to upcast it to Object. You're better of using Map classes instead. One can then wonder why Java doesn't have Map literals. The reason for that is inertia. When Java was designed in the early 90's maps and sets weren't thought of to be as useful as arrays in everyday programming.
- nostrademons 9y agoThere are two solutions to this: 1. Take the type definition from the point of use, not the declaration. For example, if the object literal is being assigned to a variable, its type is the type of the variable. If it's being passed to a function, its type is (a subtype of) the type of the function parameter. If it's being returned, it's the return type of the current function. C/C++ and Kotlin do this, as does Scala (I think; I don't know the language well). 2. Use structural subtyping. In the type system, allow the possibility of expressing "HasField x && HasField y && HasField z". Then the type of the object literal is simply an anonymous type that includes those predicates. Ocaml and (I think) Go do this.
- bjourne 9y agoAh, you're right in case the syntax is for instantiating objects of existing classes/structs. My take was that the OP wanted the object literals to be able to create new types. In Javascript, var a = { x: 123, y: 456 } is meaningful without a prior class declaration.