Groovy web console

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

GroovyExample1

Published 3 months ago by kenanhancer
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def name = "John"
def s1 = "Hello $name" // $name will be replaced
def s2 = 'Hello $name' // $name will not be replaced

println s1
println s2
println s1.class
println s2.class

def date = new Date()

println "We met at $date"
println "We met at ${date.format('MM/dd/yy')}"

public class Person{
    String firstName
    String lastName
    int age
    def address
}

Person p = new Person()

// use the generated access methods
p.setFirstName("Lars")

// this will still use the generated access method, it is not a direct access!
p.lastName = "Vogel"

p.address = ("Homestreet 3")

println(p.firstName + " " + p.lastName)

// use the generated constructor
p = new Person(firstName: "Peter", lastName:"Mueller");

println(p.firstName + " " + p.lastName);



def mylist= [1,2,"Lars","4"]
mylist.each{ println it }

class Math {
    static sum(a,b,c=0) {
        a+b+c;
    }
}

println Math.sum(1,5)
println Math.sum(1,2,5)

// valid variable definitions  
// typed 
String name3
int x 
Integer y  

// untyped 
def list 
def map 
def todo

10.times {println "Test"}

for (i in 0..9) {
    println ("Hello $i" )
}

assert 'B'..'E' == ['B', 'C', 'D', 'E']

for (a in 'B'..'E') {
    println ("$a")
}

class PersonV2{     
    String firstName;    
    String lastName;  

    PersonV2(String firstName, String lastName){         
        this.firstName = firstName         
        this.lastName= lastName     
    } 
}

List<Integer> listv2 = [1,2,3,4]
println listv2[0]
println listv2[1]         
println listv2[2]



def String[] strings = "This is a long sentence".split()

// convert Array to list 
def List listStrings = strings 
// convert List back to Array 
def String[] arrayStrings = listStrings

println strings.class.name 
println listStrings.class.name 
println arrayStrings.class.name


def listv3 = ["Hello", "Test", "Lars"]  
// calculate the length of every String in the list 
def sizeList = listv3*.size() 

assert sizeList == [5, 4, 4]


def l1 = ['test', 12, 20, true] 
// check with grep that one element is a Boolean 
assert [true] == l1.grep(Boolean)

// grep for all elements which start with a pattern
assert ['Groovy'] == ['test', 'Groovy', 'Java'].grep(~/^G.*/)

// grep for if the list contains b and c 
assert ['b', 'c'] == ['a', 'b', 'c', 'd'].grep(['b', 'c'])

// grep for elements which are contained in the range
assert [14, 16] == [5, 14, 16, 75, 12].grep(13..17)

// grep for elements which are equal to 42.031
assert [42.031] == [15, 'Peter', 42.031, 42.032].grep(42.031)

// grep for elements which are larger than 40 based on the closure
assert [50, 100, 300] == [10, 12, 30, 50, 100, 300].grep({ it > 40 })

// create map
def mapv2 = ["Jim":"Knopf", "Thomas":"Edison"]

// the dot operator is overloaded to access the value         
mapv2.AnotherKey="Testing"

// create map without quotes for the keys
def anotherMap = [Jim:"Knopf", Thomas:"Edison"]

// size is used to determine the number of elements
assert anotherMap.size() == 2

// if key should be evaluated put it into brackets
def xv2 ="a"

// not true, as x is interpreted as "x"
println ([a:1]==[xv2:1])

// force Groovy to see x as expression
println ([a:1]==[(xv2):1])

// create empty map         
def emptyMap = [:]




def mymap = [1:"Jim Knopf", 2:"Thomas Edison", 3:"Lars Vogel"]         
mymap.each {entry -> println (entry.key > 1)}         
mymap.each {entry -> println (entry.value.contains("o"))}         
println "Lars contained:" + mymap.any {entry -> entry.value.contains("Lars")}         
println "Every key small than 4:" + mymap.every {entry -> entry.key < 4}


def result =''         
for (key in mymap.keySet()) {             
    result += key         
}         

println result          

mymap.each { key, value ->             
    print key + " "             
    println value         
}          

mymap.each { entry ->             
    print entry.key + " "             
    println entry.value         
}


class Address {     
    String street, city 
}  

class PersonV3 {     
    String name     
    Address address     
    String phoneNumber      
    
    def moveToNewPlace(inputAsMap, newPhoneNumber) {         
        address.street = inputAsMap.street         
        address.city   = inputAsMap.city         
        phoneNumber = newPhoneNumber      
    } 
}

def address = new Address(street: 'Reeperbahn', city: 'Hamburg')
def pv2 = new PersonV3(name: 'Lars', address: address, phoneNumber: '123456789')

// Groovy translates the following call to: 
// p.move([street: 'Saselbeck', city: 'Hamburg'], '23456789') 
// p.moveToNewPlace(street: 'Saselbeck', '23456789', city: 'Hamburg')