How does the Groovy in operator work?

前端 未结 3 1485
花落未央
花落未央 2021-01-11 10:22

The Groovy \"in\" operator seems to mean different things in different cases. Sometimes x in y means y.contains(x) and sometimes it seems to call

相关标签:
3条回答
  • 2021-01-11 10:54

    It's actually all based on isCase. Groovy adds an isCase method to Collections that is based on the contains method. Any class with isCase can be used with in.

    0 讨论(0)
  • 2021-01-11 11:07

    I did some experimentation and it looks like the in operator is based on the isCase method only as demonstrated by the following code

    class MyList extends ArrayList {
        boolean isCase(Object val) {
            return val == 66
        }
    }
    
    def myList = new MyList()
    myList << 55
    55 in myList // Returns false but myList.contains(55) returns true     
    66 in myList // Returns true but myList.contains(66) returns false
    

    For the JDK collection classes I guess it just seems like the in operator is based on contains() because isCase() calls contains() for those classes.

    0 讨论(0)
  • 2021-01-11 11:07

    in is the "Membership operator".

    From the documentation for Groovy 3 (emphasis mine):

    8.6. Membership operator

    The membership operator (in) is equivalent to calling the isCase method. In the context of a List, it is equivalent to calling contains, like in the following example:

    def list = ['Grace','Rob','Emmy']
    assert ('Emmy' in list)           # (1)    
    

    (1) equivalent to calling list.contains('Emmy') or list.isCase('Emmy')

    So, Groovy always calls isCase, which in case of a List maps to contains.

    0 讨论(0)
提交回复
热议问题