groovy 入门简单介绍

2019-01-14  本文已影响15人  望月成三人

环境搭建

Intellij

goovvyBean

class Book {
    String title
}
def groovyBook = new Book()
groovyBook.setTitle("hello word")
println(groovyBook.getTitle())

GString

字符串中的占位符,并能自动解析

def nick = "shark"
def book = "groovy in action"
println("$nick is $book")

数字也是对象

groovy中所有数字都是对象,不像java中有专用类型,groovy自动装箱和拆箱

def x = 2
println(x.toString().length())

range

groovy独有的,可以叫它范围,和for类似

def x = 1..10
x.each {
    println("$it")
}

闭包

def str = ''
(9..5).each{element->
    str+=element
}
println(str)

结构控制

package groovy
//if-else
if (1 > 2) {
    println("真")
} else {
    println("假")
}

// while
def i = 0
while (i < 5) {
    println("while"+i)
    i ++
}

// 迭代range
def result = 0
def rangers = 0..9
for (item in rangers) {
    result += item
}
println("迭代range="+result)

// 迭代list

def list = [1, 2, 3, 4, 5]
for (item in list) {
    println("迭代list="+item)
}

//switch

def key = 5
switch (key) {
    case 1: println("good"); break
    case 2: println("bad"); break
    default: println("haha")
}

新建groovy class和java class区别

上一篇 下一篇

猜你喜欢

热点阅读