為了了解 Groovy 的基本語(yǔ)法,讓我們先看看一個(gè)簡(jiǎn)單的 Hello World 程序。
創(chuàng)建Hello World程序,你只要輸入以下幾行簡(jiǎn)單的代碼就可實(shí)現(xiàn) -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
當(dāng)我們運(yùn)行上面的程序,我們會(huì)得到以下結(jié)果 -
Hello World
import 語(yǔ)句可以用來(lái)導(dǎo)入,可以讓你的代碼使用其他庫(kù)的功能。這是通過(guò)使用在 Import 關(guān)鍵字完成。
下面的示例演示了如何使用 MarkupBuilder 的類(lèi),它可能是最常用的創(chuàng)建 HTML 或 XML 標(biāo)記的類(lèi)之一。
import groovy.xml.MarkupBuilder def xml = new MarkupBuilder()
默認(rèn)情況下,Groovy 在代碼中包括以下庫(kù),因此您不需要顯式導(dǎo)入它們。
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
令牌可以是一個(gè)關(guān)鍵字,一個(gè)標(biāo)識(shí)符,常量,字符串文字或符號(hào)。
println(“Hello World”);
在上面的代碼行中,有兩個(gè)令牌,首先是關(guān)鍵詞的 println 而接下來(lái)就是字符串的“Hello World”。
在您的代碼中使用注釋。Groovy 的注釋可以是單行或多行。
單行注釋使用 // 在該行的任何位置來(lái)識(shí)別。一個(gè)例子如下所示 -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
多行注釋標(biāo)識(shí)與在開(kāi)始 / * 和 * / 識(shí)別多行注釋的末尾。
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 編程語(yǔ)言,它需要具有分號(hào)在 Groovy 定義多個(gè)語(yǔ)句之間進(jìn)行區(qū)分。
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'); } }
上述例子示出了分號(hào)使用了不同行的代碼語(yǔ)句之間進(jìn)行區(qū)分。
標(biāo)識(shí)符被用來(lái)定義變量,函數(shù)或其他用戶(hù)定義的變量。標(biāo)識(shí)符以字母開(kāi)頭,美元或下劃線。他們不能以數(shù)字開(kāi)頭。以下是有效標(biāo)識(shí)符的一些例子
def employeename def student1 def student_name
其中,DEF 是在 Groovy 用來(lái)定義標(biāo)識(shí)符的關(guān)鍵字。
下面是一個(gè)如何在我們的 Hello World 程序中使用標(biāo)識(shí)符的代碼示例。
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 被用作標(biāo)識(shí)符。
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 |
空白是在編程語(yǔ)言如 Java 和 Groovy 用來(lái)形容空格,制表符,換行符和注釋術(shù)語(yǔ)??崭穹指魪牧硪粋€(gè)聲明的一部分,使編譯器,其中一個(gè)元素標(biāo)識(shí)的聲明。
例如,在下面的代碼示例,存在關(guān)鍵字 def 和變量 x 之間的空白。這是為了讓編譯器知道 DEF 是需要被使用,并且是 x 應(yīng)該是需要被定義的變量名的關(guān)鍵字。
def x = 5;
文字是在 groovy 中表示固定值的符號(hào)。Groovy 語(yǔ)言有符號(hào)整數(shù),浮點(diǎn)數(shù),字符和字符串。下面是一些在 Groovy 編程語(yǔ)言文字的例子 -
12 1.45 ‘a(chǎn)’ “aa”
更多建議: