You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2023/10/17 19:16:59 UTC

[groovy] branch master updated: GROOVY-11196: `tap`/`with`/`identity` propagates `null` not `NullObject`

This is an automated email from the ASF dual-hosted git repository.

emilles pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git


The following commit(s) were added to refs/heads/master by this push:
     new cf18e8850d GROOVY-11196: `tap`/`with`/`identity` propagates `null` not `NullObject`
cf18e8850d is described below

commit cf18e8850d3a0ffe51f327cea757855509335172
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Oct 17 13:47:46 2023 -0500

    GROOVY-11196: `tap`/`with`/`identity` propagates `null` not `NullObject`
---
 .../groovy/runtime/DefaultGroovyMethods.java       |  93 ++++----
 .../org/codehaus/groovy/runtime/NullObject.java    | 162 ++++++-------
 src/test/groovy/bugs/Groovy11196.groovy            |  42 ++++
 .../codehaus/groovy/runtime/NullObjectTest.groovy  | 259 ++++++++++++++-------
 4 files changed, 351 insertions(+), 205 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index fe85338d06..a8db52c4c9 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -261,6 +261,19 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
         return closure.call(entry);
     }
 
+    // internal helper method
+    private static <T, U> Tuple2<T, U> callWithDelegateAndParameter(Closure<T> closure, U object) {
+        if (object == NullObject.getNullObject()) {
+            object = null; // GROOVY-4526, et al.
+        }
+        @SuppressWarnings("unchecked")
+        final Closure<T> clone = (Closure<T>) closure.clone();
+        clone.setResolveStrategy(Closure.DELEGATE_FIRST);
+        clone.setDelegate(object);
+        T result = clone.call(object);
+        return new Tuple2<>(result, object);
+    }
+
     //--------------------------------------------------------------------------
     // abs
 
@@ -2258,7 +2271,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
     public static <K, V, E> Map<K, V> collectEntries(Iterator<E> self, Map<K, V> collector, Function<? super E, K> keyTransform, Function<? super E, V> valueTransform) {
         while (self.hasNext()) {
             E element = self.next();
-            addEntry(collector, Tuple2.tuple(keyTransform.apply(element), valueTransform.apply(element)));
+            addEntry(collector, new Tuple2<>(keyTransform.apply(element), valueTransform.apply(element)));
         }
         return collector;
     }
@@ -2327,7 +2340,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      */
     public static <K, V, X, Y> Map<K, V> collectEntries(Map<X, Y> self, Map<K, V> collector, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform) {
         for (Map.Entry<X, Y> entry : self.entrySet()) {
-            addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), valueTransform.apply(entry.getValue())));
+            addEntry(collector, new Tuple2<>(keyTransform.apply(entry.getKey()), valueTransform.apply(entry.getValue())));
         }
         return collector;
     }
@@ -2445,7 +2458,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      */
     public static <K, V> Map<K, V> collectKeys(Map<K, V> keys, Map<K, V> collector, Function<? super K, K> keyTransform) {
         for (Map.Entry<K, V> entry : keys.entrySet()) {
-            addEntry(collector, Tuple2.tuple(keyTransform.apply(entry.getKey()), entry.getValue()));
+            addEntry(collector, new Tuple2<>(keyTransform.apply(entry.getKey()), entry.getValue()));
         }
         return collector;
     }
@@ -2716,7 +2729,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      */
     public static <K, V> Map<K, V> collectValues(Map<K, V> keys, Map<K, V> collector, Function<? super V, V> valueTransform) {
         for (Map.Entry<K, V> entry : keys.entrySet()) {
-            addEntry(collector, Tuple2.tuple(entry.getKey(), valueTransform.apply(entry.getValue())));
+            addEntry(collector, new Tuple2<>(entry.getKey(), valueTransform.apply(entry.getValue())));
         }
         return collector;
     }
@@ -7021,14 +7034,11 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      * @see #with(Object, Closure)
      * @since 1.0
      */
-    public static <T,U> T identity(
-            @DelegatesTo.Target("self") U self,
-            @DelegatesTo(value=DelegatesTo.Target.class,
-                    target="self",
-                    strategy=Closure.DELEGATE_FIRST)
-            @ClosureParams(FirstParam.class)
-                    Closure<T> closure) {
-        return DefaultGroovyMethods.with(self, closure);
+    public static <T, U> T identity(
+            @DelegatesTo.Target U self,
+            @DelegatesTo(strategy=Closure.DELEGATE_FIRST)
+            @ClosureParams(FirstParam.class) Closure<T> closure) {
+        return callWithDelegateAndParameter(closure,self).getV1();
     }
 
     //--------------------------------------------------------------------------
@@ -11501,7 +11511,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
             } else {
                 metaClassRegistry.setMetaClass(self, metaClass);
             }
-            if (self==NullObject.class) {
+            if (NullObject.class.equals(self)) {
                 NullObject.getNullObject().setMetaClass(metaClass);
             }
         }
@@ -13006,15 +13016,11 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      * @see #with(Object, Closure)
      * @since 2.5.0
      */
-    @SuppressWarnings("unchecked")
-    public static <T,U> U tap(
-            @DelegatesTo.Target("self") U self,
-            @DelegatesTo(value=DelegatesTo.Target.class,
-                    target="self",
-                    strategy=Closure.DELEGATE_FIRST)
-            @ClosureParams(FirstParam.class)
-            Closure<T> closure) {
-        return (U) with(self, true, (Closure<Object>)closure);
+    public static <T, U> U tap(
+            @DelegatesTo.Target U self,
+            @DelegatesTo(strategy=Closure.DELEGATE_FIRST)
+            @ClosureParams(FirstParam.class) Closure<T> closure) {
+        return callWithDelegateAndParameter(closure,self).getV2();
     }
 
     //--------------------------------------------------------------------------
@@ -15271,15 +15277,11 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      * @see #tap(Object, Closure)
      * @since 1.5.0
      */
-    @SuppressWarnings("unchecked")
-    public static <T,U> T with(
-            @DelegatesTo.Target("self") U self,
-            @DelegatesTo(value=DelegatesTo.Target.class,
-                    target="self",
-                    strategy=Closure.DELEGATE_FIRST)
-            @ClosureParams(FirstParam.class)
-            Closure<T> closure) {
-        return (T) with(self, false, (Closure<Object>)closure);
+    public static <T, U> T with(
+            @DelegatesTo.Target U self,
+            @DelegatesTo(strategy=Closure.DELEGATE_FIRST)
+            @ClosureParams(FirstParam.class) Closure<T> closure) {
+        return callWithDelegateAndParameter(closure,self).getV1();
     }
 
     /**
@@ -15312,28 +15314,21 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
      * </pre>
      * Alternatively, 'with' is an alias for 'with(false)', so the boolean parameter can be omitted instead.
      *
-     * @param self      the object to have a closure act upon
-     * @param returning if true, return the self object; otherwise, the result of calling the closure
-     * @param closure   the closure to call on the object
-     * @return the self object or the result of calling the closure depending on 'returning'
+     * @param self     the object to have a closure act upon
+     * @param returnIt if true, return the self object; otherwise, the result of calling the closure
+     * @param closure  the closure to call on the object
+     * @return the self object or the result of calling the closure depending on {@code returnIt}
      * @see #with(Object, Closure)
      * @see #tap(Object, Closure)
      * @since 2.5.0
      */
-    public static <T,U extends T, V extends T> T with(
-            @DelegatesTo.Target("self") U self,
-            boolean returning,
-            @DelegatesTo(value=DelegatesTo.Target.class,
-                    target="self",
-                    strategy=Closure.DELEGATE_FIRST)
-            @ClosureParams(FirstParam.class)
-            Closure<T> closure) {
-        @SuppressWarnings("unchecked")
-        final Closure<V> clonedClosure = (Closure<V>) closure.clone();
-        clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST);
-        clonedClosure.setDelegate(self);
-        V result = clonedClosure.call(self);
-        return returning ? self : result;
+    public static <T, U extends T, V extends T> T with(
+            @DelegatesTo.Target U self, boolean returnIt,
+            @DelegatesTo(strategy=Closure.DELEGATE_FIRST)
+            @ClosureParams(FirstParam.class) Closure<V> closure) {
+        var response = callWithDelegateAndParameter(closure,self);
+        if (returnIt) return response.getV2(); // self or null
+        return response.getV1();
     }
 
     //--------------------------------------------------------------------------
diff --git a/src/main/java/org/codehaus/groovy/runtime/NullObject.java b/src/main/java/org/codehaus/groovy/runtime/NullObject.java
index 30343852b1..a95b67ff40 100644
--- a/src/main/java/org/codehaus/groovy/runtime/NullObject.java
+++ b/src/main/java/org/codehaus/groovy/runtime/NullObject.java
@@ -25,8 +25,18 @@ import java.util.Collections;
 import java.util.Iterator;
 
 public class NullObject extends GroovyObjectSupport {
+
     private static final NullObject INSTANCE = new NullObject();
 
+    /**
+     * get the NullObject reference
+     *
+     * @return the null object
+     */
+    public static NullObject getNullObject() {
+        return INSTANCE;
+    }
+
     /**
      * private constructor
      */
@@ -36,151 +46,147 @@ public class NullObject extends GroovyObjectSupport {
         }
     }
 
+    //--------------------------------------------------------------------------
+
     /**
-     * get the NullObject reference
+     * Since this is implemented as a singleton, avoid the use of the clone method.
      *
-     * @return the null object
+     * @return never
+     * @throws NullPointerException
      */
-    public static NullObject getNullObject() {
-        return INSTANCE;
+    @Override
+    public Object clone() {
+        throw new NullPointerException("Cannot invoke method clone() on null object");
     }
 
     /**
-     * Since this is implemented as a singleton, we should avoid the
-     * use of the clone method
+     * null is only equal to null.
+     *
+     * @param o the reference object with which to compare
+     * @return true if this object is the same as the to argument
      */
     @Override
-    public Object clone() {
-        throw new NullPointerException("Cannot invoke method clone() on null object");
+    public boolean equals(final Object o) {
+        return o == null || o == INSTANCE;
     }
 
     /**
-     * Tries to get a property on null, which will always fail
-     *
-     * @param property - the property to get
-     * @return a NPE
+     * @return never
+     * @throws NullPointerException
      */
     @Override
-    public Object getProperty(String property) {
-        throw new NullPointerException("Cannot get property '" + property + "' on null object");
+    public int hashCode() {
+        throw new NullPointerException("Cannot invoke method hashCode() on null object");
+    }
+
+    @Override
+    public String toString() {
+        return "null";
     }
 
     /**
-     * Allows the closure to be called for NullObject
+     * Tries to get a property on null, which will always fail.
      *
-     * @param closure the closure to call on the object
-     * @return result of calling the closure
+     * @return never
+     * @throws NullPointerException
      */
-    public <T> T with( Closure<T> closure ) {
-        return DefaultGroovyMethods.with( null, closure ) ;
+    @Override
+    public Object getProperty(final String name) {
+        throw new NullPointerException("Cannot get property '" + name + "' on null object");
     }
 
     /**
      * Tries to set a property on null, which will always fail
      *
-     * @param property - the property to set
-     * @param newValue - the new value of the property
+     * @throws NullPointerException
      */
     @Override
-    public void setProperty(String property, Object newValue) {
-        throw new NullPointerException("Cannot set property '" + property + "' on null object");
+    public  void  setProperty(final String name, final Object value) {
+        throw new NullPointerException("Cannot set property '" + name + "' on null object");
     }
 
     /**
-     * Tries to invoke a method on null, which will always fail
+     * Tries to invoke a method on null, which will always fail.
      *
-     * @param name the name of the method to invoke
-     * @param args - arguments to the method
-     * @return a NPE
+     * @return never
+     * @throws NullPointerException
      */
     @Override
-    public Object invokeMethod(String name, Object args) {
+    public Object invokeMethod(final String name, final Object arguments) {
         throw new NullPointerException("Cannot invoke method " + name + "() on null object");
     }
 
+    //--------------------------------------------------------------------------
+
     /**
-     * null is only equal to null
+     * A null object coerces to false.
      *
-     * @param to - the reference object with which to compare
-     * @return - true if this object is the same as the to argument
+     * @return false
      */
-    @Override
-    public boolean equals(Object to) {
-        return to == null;
+    public boolean asBoolean() {
+        return false;
     }
 
     /**
-     * iterator() method to be able to iterate on null.
-     * Note: this part is from Invoker
+     * Type conversion method for null.
      *
-     * @return an iterator for an empty list
+     * @return null
      */
-    public Iterator iterator() {
-        return Collections.EMPTY_LIST.iterator();
+    public Object asType(final Class c) {
+        if (c.isPrimitive()) throw new IllegalArgumentException("null to " + c);
+        return null;
     }
 
     /**
-     * Allows to add a String to null.
-     * The result is concatenated String of the result of calling
-     * toString() on this object and the String in the parameter.
+     * Tests for equal references.
      *
-     * @param s - the String to concatenate
-     * @return the concatenated string
+     * @return true if object is null
      */
-    public Object plus(String s) {
-        return getMetaClass().invokeMethod(this, "toString", new Object[]{}) + s;
+    public boolean is(final Object o) {
+        return equals(o);
     }
 
     /**
-     * Fallback for null+null.
-     * The result is always a NPE. The plus(String) version will catch
-     * the case of adding a non-null String to null.
+     * iterator() method to be able to iterate on null.
+     * Note: this part is from Invoker
      *
-     * @param o - the Object
-     * @return nothing
+     * @return an empty iterator
      */
-    public Object plus(Object o) {
-        throw new NullPointerException("Cannot execute null+" + o);
+    public Iterator iterator() {
+        return Collections.emptyIterator();
     }
 
     /**
-     * The method "is" is used to test for equal references.
-     * This method will return true only if the given parameter
-     * is null
+     * Fallback for {@code null+null}. The {@link plus(String)} variant catches
+     * the case of adding a non-null String to null.
      *
-     * @param other - the object to test
-     * @return true if other is null
+     * @return never
+     * @throws NullPointerException
      */
-    public boolean is(Object other) {
-        return other == null;
+    public Object plus(final Object o) {
+        throw new NullPointerException("Cannot execute null+" + o);
     }
 
     /**
-     * Type conversion method for null.
+     * Allows to add a String to null.
+     * The result is concatenated String of the result of calling
+     * toString() on this object and the String in the parameter.
      *
-     * @param c - the class to convert to
-     * @return always null
+     * @return the concatenated string
      */
-    public Object asType(Class c) {
-        return null;
+    public Object plus(final String s) {
+        return getMetaClass().invokeMethod(this, "toString", new Object[0]) + s;
     }
 
     /**
-     * A null object always coerces to false.
+     * Allows the closure to be called for NullObject.
      *
-     * @return false
+     * @param closure the closure to call on the object
+     * @return result of calling the closure
      */
-    public boolean asBoolean() {
-        return false;
-    }
 
-    @Override
-    public String toString() {
-        return "null";
-    }
-
-    @Override
-    public int hashCode() {
-        throw new NullPointerException("Cannot invoke method hashCode() on null object");
+    @Deprecated(since = "5.0.0") // GROOVY-4526
+    public <T> T with(final Closure<T> closure) {
+        return DefaultGroovyMethods.with(null, closure);
     }
 }
diff --git a/src/test/groovy/bugs/Groovy11196.groovy b/src/test/groovy/bugs/Groovy11196.groovy
new file mode 100644
index 0000000000..3f13ec1e13
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy11196.groovy
@@ -0,0 +1,42 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ */
+package groovy.bugs
+
+import org.junit.Test
+
+final class Groovy11196 {
+
+    static abstract class A {
+        abstract m(String s)
+    }
+
+    static class C extends A {
+        @Override m(String s) {
+            return 'successful'
+        }
+    }
+
+    @Test
+    void testNullParameter() {
+        null.tap {
+            Object result = new C().m(it)
+            assert result == 'successful'
+        }
+    }
+}
diff --git a/src/test/org/codehaus/groovy/runtime/NullObjectTest.groovy b/src/test/org/codehaus/groovy/runtime/NullObjectTest.groovy
index bdee23985d..495b0559b1 100644
--- a/src/test/org/codehaus/groovy/runtime/NullObjectTest.groovy
+++ b/src/test/org/codehaus/groovy/runtime/NullObjectTest.groovy
@@ -18,129 +18,232 @@
  */
 package org.codehaus.groovy.runtime
 
-import groovy.test.GroovyTestCase
+import org.junit.Test
 
-class NullObjectTest extends GroovyTestCase {
-    void testCallingMethod() {
-        def foo = null
-        shouldFail(NullPointerException) {
-          println foo.bar
+import static groovy.test.GroovyAssert.shouldFail
+
+final class NullObjectTest {
+
+    @Test
+    void testInit1() {
+        shouldFail(RuntimeException) {
+            new NullObject()
         }
     }
 
-    void testtoStringMethod() {
-        def foo = null
-        assert foo.toString() == "null"
+    @Test
+    void testInit2() {
+        shouldFail(RuntimeException) {
+            NullObject.newInstance()
+        }
     }
 
-    void testEquals() {
-        def a = [1]
-        assert a[3] == a[4]
-        assert a[2].equals(a[4])
+    @Test
+    void testInit3() {
+        shouldFail(NoSuchMethodException) {
+            NullObject.getConstructor()
+        }
     }
 
-    void testAsExpression() {
-      assert null as String == null
+    @Test
+    void testClone() {
+        def nil = null
+        shouldFail(NullPointerException) {
+            nil.clone()
+        }
     }
 
-    void testIs(){
-      assert null.is(null)
+    @Test
+    void testEquals() {
+        def nil = null
+        assert nil == nil
+        assert nil == null
+        assert null == nil
+        assert null == null
+        assert !nil.equals(0)
+        assert !nil.equals('')
+        assert nil.equals(null)
+        assert nil.equals(NullObject.getNullObject())
+    }
+
+    @Test
+    void testHashCode() {
+        def nil = null
+        shouldFail(NullPointerException) {
+            nil.hashCode()
+        }
     }
 
-    void testCategory() {
-        def n = null
-
-        assert "a $n b" == "a null b"
-            assert n.toString() == "null"
-            assert n + " is a null value" == "null is a null value"
-            assert "this is a null value " + null == "this is a null value null"
+    @Test
+    void testToString() {
+        def nil = null
+        assert nil.toString() == 'null'
+    }
 
-            use (MyCategory) {
-                assert "a $n b" == "a  b"
-                assert n.toString() == ""
-                assert n + " is a null value" == " is a null value"
-                assert "this is a null value " + null == "this is a null value "
-            }
+    @Test
+    void testGetProperty() {
+        def nil = null
+        shouldFail(NullPointerException) {
+            nil.foo
         }
+    }
 
-    void testClone() {
-        def foo = null
+    @Test
+    void testSetProperty() {
+        def nil = null
         shouldFail(NullPointerException) {
-            foo.clone()
+            nil.foo = 'bar'
         }
     }
 
-    void testInstantiation1() {
-        shouldFail(RuntimeException) {
-            new NullObject()
+    @Test
+    void testInvokeMethod() {
+        def nil = null
+        shouldFail(NullPointerException) {
+            nil.foo()
         }
     }
 
-    void testInstantiation2() {
-        shouldFail(RuntimeException) {
-            NullObject.newInstance()
-        }
+    //
+
+    @Test
+    void testAsBool() {
+        def nil = null
+        assert !nil
+        assert !nil.asBoolean()
     }
 
-    void testInstantiation3() {
-        shouldFail(NoSuchMethodException) {
-            NullObject.getConstructor()
+    @Test
+    void testAsType1() {
+        def nil = null
+        assert (nil as Number) == null
+        assert (nil as String) == null
+    }
+
+    @Test
+    void testAsType2() {
+        def nil = null
+        shouldFail(IllegalArgumentException) {
+            NullObject.getNullObject().asType(int.class)
         }
     }
 
-    void testEMC() {
-        def oldMC = null.getMetaClass()
-        NullObject.metaClass.hello = { -> "Greeting from null" }
-        assert null.hello() == "Greeting from null"
-        null.setMetaClass(oldMC)
+    @Test
+    void testIs() {
+        def nil = null
+        assert nil.is(null)
+        assert !nil.is(' ')
+        assert nil.is(NullObject.getNullObject())
+    }
+
+    @Test
+    void testIterator() {
+        def nil = null
+        assert !nil.iterator().hasNext()
     }
 
-    void testNullPlusNull() {
-        String message = shouldFail(NullPointerException) {
+    @Test
+    void testPlus1() {
+        def err = shouldFail(NullPointerException) {
             null+null
         }
-        assert message == "Cannot execute null+null"
+        assert err.message == 'Cannot execute null+null'
     }
 
-    void testNullPlusNumber() {
-      String message = shouldFail(NullPointerException) {
-          null+1
-      }
-      assert message == "Cannot execute null+1"
+    @Test
+    void testPlus2() {
+        def err = shouldFail(NullPointerException) {
+            null+1
+        }
+        assert err.message == 'Cannot execute null+1'
     }
 
-    void testNullWith() {
-        def map = [ a:1, b:2 ]
-        map.c.with { c ->
-            assert c == null
+    @Test
+    void testPlus3() {
+        assert (null + '!') == 'null!'
+    }
+
+    // GROOVY-11196
+    @Test
+    void testTap() {
+        def nil = null
+        nil = nil.tap {
+            assert it === null
+            assert it !instanceof NullObject
         }
-        def a = null.with {
-            assert !(it instanceof NullObject)
-            2
+        assert nil === null
+        assert nil !instanceof NullObject
+    }
+
+    // GROOVY-4526, GROOVY-4985
+    @Test
+    void testWith() {
+        def nil = null
+        def ret = nil.with { it ->
+            assert it === null
+            assert it !instanceof NullObject
         }
-        assert a == 2
+        assert ret === null
+        assert ret !instanceof NullObject
+
+        ret = nil.with {
+            assert it === null
+            assert it !instanceof NullObject
+            return 2
+        }
+        assert ret == 2
     }
 
-    void testEqualsInCategory() {
-        def val = null
-        use (MyCategory) {
-            assert val.isNull()
-            assert val.isNull2()
+    //--------------------------------------------------------------------------
+
+    static class MyCategory {
+        public static String toString(NullObject obj) {
+            return ''
+        }
+
+        static boolean isNull(value) {
+            value == null
+        }
+
+        static boolean isNull2(value) {
+            null == value
         }
     }
-}
 
-class MyCategory {
-    public static String toString(NullObject obj) {
-        return ""
+    @Test
+    void testCategory1() {
+        def nil = null
+
+        assert "a $nil b" == 'a null b'
+        assert nil.toString() == 'null'
+        assert nil + ' is a null value' == 'null is a null value'
+        assert 'this is a null value ' + null == 'this is a null value null'
+
+        use (MyCategory) {
+            assert "a $nil b" == 'a  b'
+            assert nil.toString() == ''
+            assert nil + ' is a null value' == ' is a null value'
+            assert 'this is a null value ' + null == 'this is a null value '
+        }
     }
 
-    static boolean isNull(value) {
-        value == null
+    @Test
+    void testCategory2() {
+        def nil = null
+        use (MyCategory) {
+            assert nil.isNull()
+            assert nil.isNull2()
+        }
     }
 
-    static boolean isNull2(value) {
-        null == value
+    @Test
+    void testMetaClass() {
+        def oldMC = NullObject.getMetaClass()
+        try {
+            NullObject.metaClass.hello = { -> 'Greeting from null' }
+            assert null.hello() == 'Greeting from null'
+        } finally {
+            NullObject.setMetaClass(oldMC)
+        }
     }
 }
-