Groovy - 语法基础

  • 简述

    为了理解Groovy 的基本语法,我们先来看一个简单的Hello World 程序。
  • 创建您的第一个 Hello World 程序

    创建您的第一个 hello world 程序就像输入以下代码行一样简单 -
    
    class Example {
       static void main(String[] args) {
          // Using a simple println statement to print output to the console
          println('Hello World');
       }
    }
    
    当我们运行上面的程序时,我们将得到以下结果 -
    
    Hello World
    
  • Groovy 中的导入语句

    import 语句可用于导入可在您的代码中使用的其他库的功能。这是通过使用import关键字完成的。
    以下示例显示如何使用 MarkupBuilder 类的简单导入,该类可能是创建 HTML 或 XML 标记最常用的类之一。
    
    import groovy.xml.MarkupBuilder 
    def xml = new MarkupBuilder() 
    
    默认情况下,Groovy 在您的代码中包含以下库,因此您无需显式导入它们。
    
    import java.lang.* 
    import java.util.* 
    import java.io.* 
    import java.net.* 
    import groovy.lang.* 
    import groovy.util.* 
    import java.math.BigInteger 
    import java.math.BigDecimal
    
  • Groovy 中的令牌

    标记可以是关键字、标识符、常量、字符串字面量或符号。
    
    println(“Hello World”);
    
    在上面的代码行中,有两个标记,第一个是关键字 println,第二个是“Hello World”的字符串字面量。
  • Groovy 中的注释

    注释用于记录您的代码。Groovy 中的注释可以是单行或多行。
    单行注释通过在行中的任何位置使用 // 来标识。一个例子如下所示 -
    
    class Example {
       static void main(String[] args) {
          // Using a simple println statement to print output to the console
          println('Hello World');
       }
    }
    
    多行注释在开头用 /* 标识,在多行注释的结尾用 */ 标识。
    
    class Example {
       static void main(String[] args) {
          /* This program is the first program
          This program shows how to display hello world */
          println('Hello World');
       }
    }
    
  • 分号

    与 Java 编程语言不同,在每个语句结束后都没有强制性的分号,它是可选的。
    
    class Example {
       static void main(String[] args) {
          def x = 5
          println('Hello World');  
       }
    }
    
    如果执行上面的程序,main 方法中的两个语句都不会产生任何错误。
  • 身份标识

    标识符用于定义变量、函数或其他用户定义的变量。标识符以字母、美元或下划线开头。他们不能以数字开头。以下是一些有效标识符的示例 -
    
    def employeename 
    def student1 
    def student_name
    
    其中def是 Groovy 中用于定义标识符的关键字。
    下面是一个代码示例,说明如何在我们的 Hello World 程序中使用标识符。
    
    class Example {
       static void main(String[] args) {
          // One can see the use of a semi-colon after each statement
          def x = 5;
          println('Hello World'); 
       }
    }
    
    在上面的示例中,变量x用作标识符。
  • 关键词

    顾名思义,关键字是 Groovy 编程语言中保留的特殊词。下表列出了 Groovy 中定义的关键字。
    as assert break case
    catch class const continue
    def default do else
    enum extends false Finally
    for goto if implements
    import in instanceof interface
    new pull package return
    super switch this throw
    throws trait true try
    while
  • 空格

    空格是 Java 和 Groovy 等编程语言中用来描述空格、制表符、换行符和注释的术语。空格将语句的一部分与另一部分分开,使编译器能够识别一个元素在语句中的位置。
    例如,在下面的代码示例中,关键字def和变量 x 之间有一个空格。这是为了让编译器知道def是需要使用的关键字,而 x 应该是需要定义的变量名。
    
    def x = 5;
    
  • 字面量

    字面量是在 groovy 中表示固定值的符号。groovy 语言具有整数、浮点数、字符和字符串的符号。以下是 Groovy 编程语言中的一些字面量示例 -
    
    12 
    1.45 
    ‘a’ 
    “aa”