当前位置:网站首页>Introduction to groovy syntax

Introduction to groovy syntax

2022-06-22 14:37:00 Leisurely summer

1、 Introduce

Groovy since 2003 Appeared in Java field . With more than ten years of history 、 Development and experience , It is a kind of Java Syntax compatible object-oriented programming language , It can be compiled as JVM Bytecode . In a way ,Groovy Can be regarded as Java A scripted improved version of . This is because it runs in although it runs in JVM On , Because of the way it works , It can work well with Java Code and its related libraries to interoperate . Most effective Java Code can also be converted to valid Groovy Code .

Groovy Designed to be both a programming language and a scripting language . This means that you need to compile Java Different ,Groovy It can be combined with the use of all kinds of grammar sugar , It reduces a lot of work in the coding process .

Groovy and Java The biggest difference in code is Groovy More flexible , Grammar requires less , So it attracts a lot of Java Users . This means that many people enter Groovy Of Java Developers will find the process of learning it very simple . Because basically , Most object-oriented programming languages tend to follow the same syntax . This shared ideology makes it easy for developers to stay Java and Groovy Switch between , Or it can be mixed Java and Groovy.

2、groovy notes

groovy There are two kinds of comments ( And Java identical )

// Single-line comments

/**/ Multiline comment

3、groovy Statement output

Mode one (java edition )

class HelloGroovy {
    static void main(args) {
        System.out.println("Hello world")
    }

Mode two (groovy)

println "hello world"

Be careful :groovy There is no need to end with a semicolon in grammar

4、 Defining variables

Mode one

image Java Use data types to declare directly

int x = 10
String s = " Zhang San "

Mode two

Use def Keyword declaration variables ,groovy It will make your incoming data , Automatically infer variable types

def x = 3
def name = " Zhang San "

5、 Single quotation marks 、 The difference between double quotation marks and three quotation marks

5.1、 Single quotation marks

Commonly used to define strings , And java Like double quotation marks in “\” For escape characters

def name = ' measuring \' Try code '

5.2、 Double quotes

The function is the same as that of single quotation marks , In addition, it can also use ${ Variable name } Set string parameters dynamically

def testName = "call me"
def text = "Hello : ${testName}"

println testName.class // class java.lang.String
println text.class  // class org.codehaus.groovy.runtime.GStringImpl

Be careful : The data type of the first line of code is Java Medium String data type , But the data type in the second code is groovy peculiar GString data type ,GString And java Medium String Can be passed on to each other , It's transformational .

${} Expression can extend any expression

5.3、 Three quotes  

The basic function is the same as that of single quotation marks , besides , If we want to define a multi line string , When you want to keep its format , We can use three quotation marks to complete

def mail = '''\
abc
efg
'''
println(mail)

notes :groovy Use the printing method , You can wrap objects with parentheses , You can also use no parentheses , Use spaces to separate objects , The printing method can also be realized , The two functions are exactly the same .

6、 Common methods for handling strings

6.1、center( Center fill )

This is the string padding method , Parameters 1 Is how many strings to fill , Parameters 2 When filling , Objects used for filling . It has Two construction methods , A parameter construction method , Specifies how many strings to add , Fill with spaces ( When the specified number is less than the length of the string, it will not be filled )

def str = "groovy hello"
println str.center(15, "p")

6.2、padLeft( padding-left )

def str = "groovy"
println str.padLeft(8,"0")

6.3、padRight( Right fill )

def str = "groovy"
println str.padRight(8,"0")

6.4、 String comparison

def str2 = "hello"
println str > str2   //  The comparison is Unicode code , You can also use compareTo Method to compare strings 

6.5、 Get the value of the string

def str = "groovy hello"
str[0] //  Get the value of the string according to the index ,
str.getAt(4) // java The way 
str[1..4] //  Incoming range , To get the string 

6.6、 String subtraction (minus Method )

Subtraction of strings , Minus is str Contained in the str The elements of , This method can also use the operator " - " Instead of

str = "ABC999"
STR2 = "aBC999"
str.minus(str2)  //  The result is aBC

6.7、 Output strings in reverse order (reverse Method )

str.reverse() //  Output strings in reverse order 

6.7、 Capitalize the initial of a string (capitalize Method )

str.capitalize() //  Capitalize the initial of a string 

6.8、 Determine whether the string is a numeric type (isNumber Method )

str.isNumber() //  Determine whether the string is a numeric type 

6.8、 Convert a string to another type ( Be similar to java Mutual conversion of various data types in )

str3 = "8"
println str3.toInteger() //  Convert a string to another type 

notes :Groovy There are also many string manipulation methods , Here are just a few commonly used , For details, see GroovyAPI file

 

7、 Conditional statements and circular statements

Groovy in  if Conditional statements 、for and while Circular statements and Java identical , Here we mainly introduce switch..case and for Enhanced use of loop statements , as well as Groovy Its transformation .

7.1、switch..case 

groovy Medium Switch..case It can be any data type ( Than Java Medium switch..case Much stronger )

def x = 1.2345
def result
switch (x) { // groovy Medium Switch..case  It can be any data type 
    case 'foo':
        result = 'find foo'
        break
    case 'bar':
        result = 'find bar'
        break
    case [4, 5, 6, 'inlist']: //  list 
        result = 'list'
        break
    case 1..44:
        result = 'range' //  Range 
        break
    case Integer:
        result = 'integer'
        break
    case BigDecimal:
        result = 'decimal'
        break
    default: result = 'default'
}

7.2、for A loop statement loops through a range

/*
*  Cycle the range 
*/
def sum = 0
for (i in 0..9) {
    sum += i
}

7.3、for Loop statement pair List Cycle through

/*  Yes list Cycle through  */
sum = 0
for (i in [1, 2, 3, 4, 2, 3, 1, 0]) {
    sum += i
}

7.4、for Loop statement pair Map Set to cycle

/*
     Yes map Set to cycle 
*/
for (i in [" Zhang San ": 23, "lucy": 19, "Bob": 30]) {
    sum += i.value
}

原网站

版权声明
本文为[Leisurely summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221317373895.html