Groovy web console

subscribe to the feed Subscribe
to this
site
TypeCheck sanity check (via #groovywebconsole)
tweet this snippet Tweet
this
script

TypeCheck sanity check

Published 5 months ago by Jim L with tags TypeCheck strong typing
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.transform.TypeChecked;
  
def h = new Hello();
h.run();

//@TypeChecked
class Hello {
   
   def run(){
      Set<String> stringSet = methodString()
      println(stringSet)
      stringSet = methodString2()
      println(stringSet)
      Set<Integer> integerSet = methodInteger()
      println(integerSet)
      integerSet = methodInteger2()
      println(integerSet)   }

   private Set<String> methodString() {
      Set<String> stringSet = genericMethod(["one":"A","two":"B","three":"C"])
      return stringSet
   }

   private Set<String> methodString2() {
      Set<String> stringSet = this.<String>genericMethod(["one":"A","two":"B","three":"C"])
      return stringSet
   } 

   private Set<Integer> methodInteger() {
      Set<Integer> integerSet = genericMethod([1:"one", 2:"two", 3:"three"])
      return integerSet
   }

//you would think this would fail - scary!  Uncomment @TypeChecked and it does
   private Set<Integer> methodInteger2() {
      Set<Integer> integerSet = genericMethod(["one":"A","two":"2","three":"3"])
      return integerSet
   } 

   private <T> Set<T> genericMethod(Map<T, String> someArg) {
        return someArg.keySet()
    }
}