You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (JIRA)" <ji...@apache.org> on 2017/12/15 00:36:00 UTC

[jira] [Commented] (GROOVY-8416) Map-based constructor generated by @Immutable works only with HashMap

    [ https://issues.apache.org/jira/browse/GROOVY-8416?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16291843#comment-16291843 ] 

Paul King commented on GROOVY-8416:
-----------------------------------

I'll have to look at the code and tests to remember for sure but I think there is some provision made for Map-based properties, i.e. this is allowed:
{code}
@Immutable
class Point {
  TreeMap props
}

TreeMap map = [color: 'red', x: 2, y: -3]
println new Point(map)
println new Point(props: map)
{code}
So both an ordered tuple constructor (with TreeMap arg) and map-based constructor (with HashMap arg) are provided.
There are issues if props above is made a Map or HashMap for example and I think only one Map-based constructor is provided. Perhaps the assumptions behind that code can be improved though.

> Map-based constructor generated by @Immutable works only with HashMap
> ---------------------------------------------------------------------
>
>                 Key: GROOVY-8416
>                 URL: https://issues.apache.org/jira/browse/GROOVY-8416
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 2.4.13
>            Reporter: Andreas Mayer
>
> If you call the map-based constructor of an {{@Immutable}} class with a non-{{HashMap}}, it will try to set the properties via setters, which causes a {{ReadOnlyPropertyException}}. Somehow it works with {{HashMap}} or subclasses like {{LinkedHashMap}}. Why?
> {code}
> import groovy.transform.Immutable
> @Immutable
> class Point {
> 	int x
> 	int y
> }
> def coordinates = [x: 1, y: 2]
> assert coordinates instanceof LinkedHashMap
> def p1 = new Point(coordinates)
> assert p1.x == 1
> def p2 = new Point(new HashMap(coordinates))
> assert p2.x == 1
> try {
> 	new Point(new TreeMap(coordinates))
> } catch (e) {
> 	assert e instanceof ReadOnlyPropertyException
> }
> try {
> 	new Point(coordinates.asImmutable())
> } catch (e) {
> 	assert e instanceof ReadOnlyPropertyException
> }
> {code}



--
This message was sent by Atlassian JIRA
(v6.4.14#64029)