Groovy Grammar Learning (1) Basic Grammar

Groovy is very similar to java, and you can even write java code directly in groovy files, which Kotlin can't do. This chapter's basic syntax mainly talks about variable definitions, loops, strings, classes, and some differences from java syntax. This article is read on the basis of being familiar with java. If you don't know the programming language, it may be a little difficult to read.

1. Basic grammar

(1) Variables

First note a few points

  • The default permission of groovy is public, it seems that there is no default like java. The method of annotation is consistent with java.
  • No parentheses are required when calling methods, and no semicolons are required at the end of each line of code.
  • Variable definitions are defined using def, because a dynamic language will determine the type at runtime. Force the specified type to use the as keyword. The data type is consistent with java.
  • The parameters defined by the method without type can accept parameters of any type, object.
  • println is an extension method of Object, and many similar methods will be seen later.
  • a.class is equivalent to a.getClass(), which is also a syntactic sugar. Groovy's numbers seem to have become wrapper classes. The int and float types in java cannot directly call methods.
  • In groovy, == is equals, and to == need to use the is method.

  • Whether there is a def variable definition is global or not will make a difference


E.g:

class Learn1{
    static void main(args){
    def a=1;
    def b=2 as int
    def c=3.asType(String)
    def d=4 as float
    def e="1" as Integer
    def f=1 as String
    def g="1".asType(int)
    println a.class
    println b.class
    println c.class
    println d.class
    println e.class
    println f.class
    println g.class
    //测试def定义
    def c = 5
    assert c == 5
    d = 6
    assert d == 6 //def keyword optional because we're within a script context
    assert binding.variables.c == null
    assert binding.variables.d == 6

    def fun(){
        h=10
    }
    fun()
    assert binding.variables.h == 10

    }
}

result:

class java.lang.Integer
class java.lang.Integer
class java.lang.String
class java.lang.Float
class java.lang.Integer
class java.lang.String
class java.lang.Integer
(2) Circulation
1. Ordinary circulation method

groovy uses the IntRange type to perform loop operations
. The first parameter of IntRange is whether it contains the value of to, which specifically means that 2 is not included.
The other parameters can be understood after a little look.

for(i in new IntRange(false,10,2).step(2)){
    println i
}

Simple writing method The writing method
using xx..xx is actually an IntRange class.
The two writing methods are exactly the same. If the < symbol is added, it will not include 2, and if it is not added, it will include 2.

for(i in (10..<2).step(2)){
    println i
}

result:

10
8
6
4
2. The loop of the extension method

If the last parameter of the method in groovy is a closure, it can be directly connected to the outside with curly brackets. The closure can be directly understood as a piece of executable code. In fact, it is the same as the lambda expression. The default parameter is it , can not be written explicitly.

(1)times
10.times {
    print it + ' '
}

result:

0 1 2 3 4 5 6 7 8 9 
(2)step
10.step(6,-2){
    print it+" "
}

result:

10 8 

Note that both methods do not include the last value.

(3) Operator and conditional judgment
1. Operator

The operator is basically the same as java, mainly mentioning the writing method of a ternary operator. Other differences have not been found for the time being, and new ones will be added.

def t=true
println t?:false

result:

true

The difference from java is obvious. When the judgment is true, if you return yourself, you can omit it.

question mark expression

def num=null
println num?.toUpperCase()

In num==null it will return null instead of throwing an exception.

2.if conditional judgment

This can be written in groovy like this

def s=""

if(!s){
    print true
}

result:

true

In fact, the asBoolean method of the corresponding class is called here. If you want your own class to have this function, you can just write one, for example

class AsB {
    static boolean asBoolean(AsB self) {
        return true;
    }
}

Many Number wrapper classes also have this way of writing

if(1){
    println true
}

It feels the same as C++ operator bool(), so I won't mention it here.

3. switch range filtering
def age = 36
def rate

switch (age) {
    case 10..26:
        rate = 0.05
        break
    case 27..36:
        rate = 0.06
        break
    case 37..46:
        rate = 0.07
        break
}

println( rate)

Not much to say here, everyone can understand that
switch and if have the same default implementation method. isCase(switchValue)
Note that the isCase method of the content in the case is called here, and the value of switch is passed to judge.

class Score {
    def score


    boolean isCase(switchValue){
        println score
        switchValue.score<score
    }

    @Override
    public String toString() {
        return "Score{" +
                "score=" + score +
                '}';
    }
}

def s = new Score(score: 100)


switch (s) {
    case new Score(score:50):
        println '小于100'
        break;
    case new Score(score:200):
        println '大于100'
        break;
}

result:

50
200
大于100
4. Expand operator

This is a bit special, refer directly to this articlehttps: //blog.csdn.net/qq_26847293/article/details/50705071Using
the expansion operator will basically return a collection

class A{
    def b=10
}
def l=[1,3,4]*.minus(5)
def k=new A()*.b
println l
println k

result:

[-4, -2, -1]
[10]
(3) String

There are three ways to string

def a='1'
def b="2"
def c="""3"""

The final type of the single quotation mark is also String. If you want to use char, you need to use as to force it.

Double quotes can concatenate variables in the middle of a string, for example

  def k = 'a' as char
  def i = 'Gro${k}ovy'

If the middle closure is lazy evaluation, compare it.

result:

Gro${k}ovy
Grobovy
Groaovy

The three quotation marks are based on the text but take the value, so that you don't have to write escapes such as newlines.

def j = """<xml>
</xml>"""
 println j

result:

<xml>
</xml>

Subtraction is used directly, and the result is not much to say.

println "java"-"ja"

Use subscripts to get values ​​directly

 String sample = "Hello world"; 
      println(sample[4]) 
      println(sample[-1]) 
      println(sample[1..2])
      println(sample[4..2])

result:

o 
d 
el 
oll 

Execute the cmd command directly

 println "cmd /c groovy -v".execute().text

First of all, execute is an extension method of String. To execute a command, text reads the value from the inputStream. In fact, the same as the java implementation, the syntactic sugar is much simpler.
result:

Groovy Version: 2.4.15 JVM: 1.8.0_131 Vendor: Oracle Corporation OS: Windows 10

The string is split and assigned directly to the variable.

def str = 'org.codehaus.groovy:groovy-all:2.4.9'

def (group, name, version,classifier) = str.split(":")
println group
println name
println version

result

org.codehaus.groovy
groovy-all
2.4.9

Fourth, the quick way to write regular expressions

def m = 'Groovy' =~ '\\w+'

if(m.find()){
    println m.group(0)
}else {
    println "not found"
}
if("java" =~ 'j'){
    println true
}

=~ You can return the Matcher directly by connecting the regular expression. If it is followed by the if or the bool return value, it will directly return whether it is found.
result:

Groovy
true
Five, the simple definition of the use of the class
//groovy方法调用
class Person {
    def name
    def age

    def getName() {
        return name + '_'
    }

    void setName(name) {
        this.name = name
    }

    def execute(x, y, z) {
        println "$x $y $z"
    }
}


//直接指定值进行构造
def person = new Person(name: 'Jack')
println person.name
person.name = 'Jack'
println person.name
println person.'name'
//利用字符串取值
def str = 'name'
println person."$str"
println person['name']
//普通取值是调用get,@是直接取值
println person.@name
//键值对优先赋值给第一个变量
person.execute(4,x: 1, y: 2, z: 3,5)

result:

Jack_
Jack_
Jack_
Jack_
Jack_
Jack
[x:1, y:2, z:3] 4 5

The basic grammar summarizes these.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325570349&siteId=291194637