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** 關鍵字來完成的。

以下示例演示瞭如何使用 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');  
   }
}

如果你執行上述程式,主方法中的兩個語句都不會產生任何錯誤。

識別符號

識別符號用於定義變數、函式或其他使用者定義的變數。識別符號以字母、美元符號或下劃線開頭。它們不能以數字開頭。以下是一些有效識別符號的示例:

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”
廣告
© . All rights reserved.