antlr / stringtemplate4

StringTemplate 4
http://www.stringtemplate.org
Other
943 stars 229 forks source link

MapModelAdaptor comparison always fails because it is using “==” instead of value.equals() to compare an Object (value) with a String (DICT_KEY) #287

Closed kskandispersonal closed 2 years ago

kskandispersonal commented 2 years ago

I’m trying to get the ST lib to return the “key” as the fallback if it does not exist in the Map. I added the “default” key to the json w/ value “key” just as the MapModelAdaptor code suggests but the comparison always fails because it is using “==” instead of value.equals() to compare an Object(value) with a String (DICT_KEY).

        //if ( value == STGroup.DICT_KEY ) { //incorrectly returns false
        if ( value.equals(groupFile.DICT_KEY) ) {//correctly returns true
            value = property;
        }

Is there a workaround for this?? Thank you for your excellent lib!!!

Clashsoft commented 2 years ago

I think this is by design, there is a difference between default : key and default : "key" in the dictionary syntax and for good reason. Using ==, despite seeming incorrect, is the way to tell those apart.

For reference:

https://github.com/antlr/stringtemplate4/blob/9a439491acc5b17d191316c9b3a99ab7bd340477/src/org/stringtemplate/v4/STGroup.java#L105

I think it should actually be defined as new String("key") to be really correct. Creating a dictionary / Map in code and putting "key" would still use the key instead of the literal string, because string literals compare equal with == due to the constant pool. Another option would be a real sentinel like new Object().

parrt commented 2 years ago

Closing this as it seems @Clashsoft has answered.