Tuesday, 5 October 2021

Object Oriented Programming Traits in Groovy Scripting groovy training telugu 40

 Watch This Video




package com.theraldanvega.traits

class Bird implements FlyingAbility, SpeakingAbility{


package com.theraldanvega.traits

trait FlyingAbility{
String fly(){

'I am Fly'


package com.therealdanvega.traits

trait SpeakingAbility
trait SpeakingAbility{
 String speak(){
"I am Speaking"

package com.therealdanvega
import com.therealdanvega.traits.Bird

Bird b=new Bird()
assert b.fly()== "I am Flying"
assert b.speak() =="I am Speaking"

Object Oriented Programming Interface in Groovy Scripting groovy training telugu 39

 Watch This Video



package com.therealdanvega.domain
class Person{

String first, last


package com.therealdanvega.service

import com.therealdanvega.domain.Person

interface IPersonService{

Person find()
List <People> findAll()


package com.therealdanvega.service
import com.therealdanvega.domain.Person
class PersonService implements IPersonService{
Person find(){
person p= new Person(first:"Dan",last:"vega")
return p


List <People> findAll(){
person p1= new Person(first:"Dan",last:"vega")
person p2= new Person(first:"jam",last:"vega")



package com.therealdanvega

import com.therealdanvega.service.PersonService

PersonService ps=new PersonService()
println ps.find()


Object Oriented Programming Inheritance in Groovy Scripting groovy training telugu 38

 Watch This Video



// Phone.groovy

package com.therealdanvega.domain

class Phone{
String name
String os
String appStore

def powerOn(){

def powerOff(){


def ring(){


package com.therealdanvega.domain
class Iphone extends Phone{

String iosVersion
def homeButtonPressed(){

def airplay(){

def powerOn()




package com.therealdanvega
package com.therealdanvega.domain.Iphone

Iphone phone = new Iphone(name:"iphone",appStore:"Apple Store",os:"ios")
println phone

Object Oriented Programming Organizing Classes into Packages in Groovy Scripting training intelugu37

 Watch This Video



Object Oriented Programming Constructors & Methods in Groovy Scripting training telugu 36

 Watch This Video



class Person{
String first,last
Person(String fullName){
List parts =fullName.split(' ')


public void foo(String a, String b){
//do stuff
String getFullName(){
"$last $first"
def bar(){

ststic String doGoodWork(){
println "do some good work............"
List someMethod (List num=[1,,2,3] Boolean canAccessAll=false){

/*Person p= new Person ("Dan Vega")
println p */


Object Oriented Programming Classes Fields Local Variables in groovy Scripting groovy training telugu 35

 Watch This Video



class Person{
String firstName,lastName
def dob
//private |  protected |public
protected String f1,f2,f3
private Date createdOn= new Date()

static welcomeMsg="Hello"

public static final String WELCOME_MSG="HELLO"

def foo(){
String msg ="Hello"
String firstName="Dan"
println"$msg, $firstName"

def Person =new Person()

println Person.foo()

Exercise UsingControl Structures Groovy Scripting in groovy traing telugu 34

 Watch This Video



[Exercise] Control Structures
Control Structures

We used a class similar to this in a previous exercise but I think it's a short and sweet example of what we need to review in this exercise. 

Create An Account Class

create a property of type BigDecimal called balance with an initial value of 0.0

Create a method called deposit

use a conditional structure (if would work great here) to check if the amount being passed is less than zero. If it is we should catch this case because we don't want to deposit negative numbers. In this case, throw an exception.

Create another method called deposit that takes a list of amounts

use a for loop to loop over these amounts and call deposit

Now that we have our class let's test it out. You can do all of this in the same file (just don't create a file called Account.groovy) 

Create an instance of the account class

deposit a valid amount

deposit an invalid amount (what happens?)

try / catch on invalid amounts

deposit a list of amounts. 


class Account {
BigDecimal balance=0.0
def deposit(BigDecimal amount)
if(amount <0){
throw new Exception("Deposit amoubt must be greater than 0")

balance += amount
def deposit(List amounts){
for (amount in amounts){
Account checking =new Account()
println checking.blance
catch(Exception e)
println "You entet invalid amount"
println checking.blance

ExceptionHandling in Groovy Scripting grrovy training in telugu 33

 Watch This Video



def foo(){
//do stuff
throw new Exception("Foo Exception")
List log=[]
catch(Exception e){
log <<e.message
log <<'finally'
println log

//Java 7 version multiple catch block


//do something

catch (FileNotFoundException | NullPointerException)
println e.class.name
println e.message

Looping in Groovy Scripting groovy training telugu 32

 Watch This Video




List numbers=[1,2,3]
//do something

assert numbers ==[]


List nums=[1,2,3,4]
for(Integer i in 1..10){
println i
for(j in 1..5)
println j


Conditional Structure in Groovy Scripting groovy training telugu 31

 Watch This Video



// if boolean (expression) {// logic}

if (true){

println true

if (true)
println true

def age=35

if (age>=35){
println "can run president"


if (false){

println true

else {

println false

def yourage=18
println"eligible for Marriage"
println "not eligible for Marriage"

def someage=37

if(someage>= 21 && someage <35){
println "eligible for Marriage"

else if(someage >= 35){

println "run for president"

else {
println "not eligible for Marriage"


// ternary operator

def name='Dan'
def isitdan=(name.toUpperCase()=='DAN')?'YES":'NO'
println isitdan


def num=5
case 1:
println "1"

case 2:

println "2"
println "default value"


Groovy Truth in Groovy Scripting groovy training telugu 30

 Watch This Video



// Boolean

assert true

assert !false


assert ('a'=='a')
assert !('a'=='b')


assert [1]
assert ![]

assert [1:'one']
assert ![:]

assert "asd"
assert !""

assert 1
assert 3.5
assert !0

//None of the above

assert new Object()
assert null

Exercise Using Closure in Groovy Scripting groovy traing telugu 29

 Watch This Video



[Exercise] Using Closures
Closure Basics

Locate the class groovy.lang.Closure and spend a few minutes looking through documentation.

Create a Method that accepts a closure as an argument

Create a closure that performs some action

Call the method and pass the closure to it.

Create a list and use them each to iterate over each item in the list and print it out

Hint - You can use the implicit it or use your own variable

Create a map of data and iterate over it using each method. 

This method can take a closure that accepts 1 or 2 arguments. 

Use 2 arguments and print out the key and value on each line.

Demonstrate the use of curry and try to come up with an example different from the one we used in the lecture. 

Explore the GDK

In the following exercises we are going to explore the GDK to find some methods that take closures and learn how to use them. Hint - I would narrow your search to java.util.Collection, java.lang.Iterable & java.util.List

Search for the find and findAll methods.

What is the difference between the two? 

Write some code to show how they both work.

Search for the any and every methods.

What is the difference between the two? 

Write some code to show how they both work. 

Search for the method groupBy that accepts a closure

What does this method do? 

Write an example of how to use this method.

def mymethod(Closure c){
def foo={
List names=["Dan","Vega","Jhon","rashmi","rasi"]
names.each{name ->
 println name
Map teams=[baseball:"Cleveland Indians", basketball:"Cleveland Cavs", football:"Cleveland Browns"]
teams.each{k,v ->
def greet ={ String greeting, String name ->
println "$greeting,$name"

greet ("HELLO","DAN")
def sayHello=greet.curry("HELLO")

List people=[
[name:"Jame", city:"New York City"]
[name:"Jhon", city:"Cleveland"]
[name:"Mary", city:"New York City"]
[name:"Dan", city:"Cleveland"]
[name:"Ton", city:"New York City"]
[name:"Frank", city:"New York City"]
[name:"Jason", city:"Cleveland"]
println people.find{person ->person.city=="Cleveland"}
println people.findAll{person ->person.city=="Cleveland"}
println people.any{person ->person.city=="Cleveland"}
println people.every{person ->person.city=="Cleveland"}

def peopleByCity =people.groupBy{person ->person.city}
println peopleByCity

Scope of Delegate in Groovy Scripting groovy trainig telugu 28

 Watch This Video



class ScopeDemo{
def outerClosure ={
println this.class.name
println owner.class.name
println delegate.class.name
def innerClosure={
println this.class.name
println owner.class.name
println delegate.class.name
def demo=new ScopeDemo()

//other Example

def writer={
append 'Dan'
append 'lives in USA'


def append(String s){

println "append() called with argument of $s"

StringBuffer sb= new StringBuffer()

Curry Methods in Groovy Scripting groovy training telugu 27

 Watch This Video



def log={String type,Date createdOn,String  msg ->

println"$createdOn [$type]-$mgs"


log("DEBUG", new Date(),"This is my first debug statement......")

def debuglog =log.curry("DEBUG")

debuglog(new Date(),"This is my first debug statement.........")
debuglog(new Date(),"This is onOther")

def todayDebugLog= log.curry("DEBUG",new Date())
todayDebugLog("This is today Bug")

//right curry

def crazyPersonLog =log.rcurry("Why i am logging this way")
crazyPersonLog("ERROR",new Date())

//index based Curring

def typeMsgLog=log.ncurry(1,new Date())
typeMsgLog("ERROR","This is using ncurry")

Collection Methods in Groovy Scripting groovy scripting training telugu 26

 Watch This Video



//each &eachWithIndex

List nums =[2,21,44,35,8,4]
for (i in nums){
println i
nums.each{println it}

for (int j=0;j<nums.size();j++){
println "$j:${nums[j]}"

nums.eachWithIndex{num.idx ->
println "$idx:$num"


List days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
List weekend=days.findAll{it.startsWith("S")}

println days
println weekend


List number=[3,6,7,9,8]

List numsTimesTen=[]

number.each{num ->

numsTimesTen << num*10
List newTimesTen = number.collect{ num -> num*10}

println number
println numsTimesTen
println newTimesTen

Closures Parameters in Groovy Scripting groovy training telugu 25

 Watch This Video



//implict parameter

def foo={
println it


def noparass={->
println "no parss...."



def sayHello ={String first, String last ->
println "Hello, $first $last"


// Default values

def greet={String name, String greeting ="Howdy"->
println "$greeting,$name"

greet ("Dan","Hello")


def concat={String...args->

println concat('abc','def')
println concat('abc','def','gfd')

Creating Closures in Groovy Scripting groovy training telugu 24

 Watch This Video



def c ={}
println c.class.name
println c instanceof Closure

def sayHelo={ name ->

println "Hello $name"


List num=[3,4,5,6,7]
num.each({ nums ->
println nums


//closures are object

def timesTen(num,closure){
 closure{num *10}

timesTen(10,{println it})
timesTen(2,{println it})

Clousers in Groovy Scripting groovy training telugu 23

 Watch This Video




This chapter covers Groovy Closures. A closure in Groovy is an open,
anonymous, block of code that can take arguments, return a value 
and be assigned to a variable. A closure may reference variables 
declared in its surrounding scope. In opposition to the formal 
definition of a closure, Closure in the Groovy language can also 
contain free variables which are defined outside of its surrounding scope.
While breaking the formal concept of a closure, it offers a variety of 
advantages which are described in this chapter.


{ [closureParameters -> ] statements }

Exercise Collections in Groovy Scripting groovy training telugu 22

Watch This Video



[Exercise] Using Collections


If you are new to Java or Groovy the idea of an Enum might be new. An Enum is a collection of constant values. We can use this collection of constants to create ranges. I want you to do some reading up on enum's and create an enum for days of the week. ex Sunday, Monday, etc...

Create a range from that enum
Print the size of the Range
Use the contains method to see if Wednesday is in that Range
Print the from element of this range
Print the to element of this range


Create a list days (Sun - Sat)
Print out the list
Print the size of the list
Remove Saturday from the list
Add Saturday back by appending it to the list
Print out the Wednesday using its index


Create a map of days of the week
1: Sunday, 2:Monday, etc...
Print out the map
Print out the class name of the map
Print the size of the map
Is there a method that would easily print out all of the days (values)? 
Without closures you may have to look at the Java API for LinkedHashMap


enum Days{
def dayRange=Days.SUNDAY..days.SATURDAY
//for in loop
for(day in dayRange){
println day

// using Closures

dayRange.each{day ->
println day

println dayRange.size()
println dayRange.contains(Days.WEDNESDAY)
println dayRange.from
println dayRange.to


println days
println days.size()
println days
println days
println days[2]


println days

println days.getClass().getName()
println days.size()
println days.values()

Collections Map in GroovyScripting groovy training in telugu 21

 Watch This Video



Map map=[:]
println map
println map.getClass().getName()

def person =[first:"ravi",email:"[email protected]"]
println person
println person.first

println person

def emailkey="emailadress"
def whatsapp=[name:"rashmi", (emailkey):"[email protected]"]

println person.size()