Groovy 基本语法

2022-08-02 13:35 更新

为了了解 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 编程语言,它需要具有分号在 Groovy 定义多个语句之间进行区分。

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');  
   }
}

上述例子示出了分号使用了不同行的代码语句之间进行区分。

身份标识

标识符被用来定义变量,函数或其他用户定义的变量。标识符以字母开头,美元或下划线。他们不能以数字开头。以下是有效标识符的一些例子 

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'); 
   }
}

在上述的例子中,变量 被用作标识符。

关键词

关键字作为名称建议是在 Groovy 编程语言中保留的特殊字。 下表列出了在 Groovy 中定义的关键字。

asassertbreakcase
catchclassconstcontinue
defdefaultdoelse
enumextendsfalseFinally
forgotoifimplements
importininstanceofinterface
newpullpackagereturn
superswitchthisthrow
throwstraittruetry
while   

空白

空白是在编程语言如 Java 和 Groovy 用来形容空格,制表符,换行符和注释术语。空格分隔从另一个声明的一部分,使编译器,其中一个元素标识的声明。

例如,在下面的代码示例,存在关键字 def 和变量 x 之间的空白。这是为了让编译器知道 DEF 是需要被使用,并且是 x 应该是需要被定义的变量名的关键字。

def x = 5;

文字

文字是在 groovy 中表示固定值的符号。Groovy 语言有符号整数,浮点数,字符和字符串。下面是一些在 Groovy 编程语言文字的例子 -

12 
1.45 
‘a’ 
“aa”


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号