groovy_day1

1、注释

单行注释

println "hello" // a comment till the end of the line
多行注释
println "hello" /* a multiline comment starting
                   at the end of a statement */

 println 1 /* one */ + 2 /* two */

文档注释
class Person {
    /** the name of the person */
    String name

    /**
     * Creates a greeting method for a certain person.
     *
     * @param otherPerson the person to greet
     * @return a greeting message
     */
    String greet(String otherPerson) {
       "Hello ${otherPerson}"
    }
}
关键字


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

null

package

return

super

switch

this

throw

throws

trait

true

try

while



变量名


def name
def item3
def with_underscore
def $dollarStart

错误的英法
def 3tier
def a+b
def a#b

还可以对象点的形式
foo.as
foo.assert
foo.break
foo.case
foo.catch


可以用"" '' 包含在变量名中
def map = [:]

map."an identifier with a space and double quotes" = "ALLOWED"
map.'with-dash-signs-and-single-quotes' = "ALLOWED"

assert map."an identifier with a space and double quotes" == "ALLOWED"
assert map.'with-dash-signs-and-single-quotes' == "ALLOWED"

map.'single quote'
map."double quote"
map.'''triple single quote'''
map."""triple double quote"""
map./slashy string/
map.$/dollar slashy string/$

插入字符


def firstname = "Homer"
map."Simson-${firstname}" = "Homer Simson"

assert map.'Simson-Homer' == "Homer Simson"


string

单引号是不支持插入字符的

'a single quoted string'

所有的字符串都可以+

assert 'ab' == 'a' + 'b'

三个单引号的字符串(不支持插值)
'''a triple single quoted string'''

三个单引号是原样子输出,没有忽略换行和串联

def startingAndEndingWithANewline = '''
line one
line two
line three
'''

你可以使用String#stripIndent()String#stripMargin()去掉换行或者空格


你可以\来去掉换行

def strippedFirstNewline = '''\
line one
line two
line three
'''

转移字符


Escape sequence

 Character

'\t'

tabulation

'\b'

backspace

'\n'

newline

'\r'

carriage return

'\f'

formfeed

'\\'

backslash

'\''

single quote (for single quoted and triple single quoted strings)

'\"'

double quote (for double quoted and triple double quoted strings)



“”双引号  支持插入

def name = 'Guillaume' // a plain string
def greeting = "Hello ${name}"

assert greeting.toString() == 'Hello Guillaume'

插入时候支持表达式(不建议)

def sum = "The sum of 2 and 3 equals ${2 + 3}"
assert sum.toString() == 'The sum of 2 and 3 equals 5'

"The sum of 1 and 2 is equal to ${def a = 1; def b = 2; a + b}"


除了使用${},也可以

def person = [name: 'Guillaume', age: 36]
assert "$person.name is $person.age years old" == 'Guillaume is 36 years old'


但是你不可以

$person.name.toString();会报错误MissingPropertyException
你可以理解为
"$number.toString()"会被groovy解析为"${number.toString}()"




如果你不许忘$或者${}能被解析,那么

assert '${name}' == "\${name}"


类似lamdba的形式

def sOneParamClosure = "1 + 2 == ${ w -> w << 3}" 
assert sOneParamClosure == '1 + 2 == 3'

这里左移被重载为

public static StringBuffer leftShift(String self, Object value) {
    return (new StringBuffer(self)).append(value);
}
除了能使用表达式,还有一种方式 懒加载


def number = 1 
def eagerGString = "value == ${number}"
def lazyGString = "value == ${ -> number }"

assert eagerGString == "value == 1" 
assert lazyGString ==  "value == 1" 

number = 2 
assert eagerGString == "value == 1" 
assert lazyGString ==  "value == 2" //这里表示闭包中的参数是关联Gstring对象指针的 
可能相当于lazyGString带有指针参数(number)的Gstring对象,eagerGString是值引用的参数 groovy是一切皆对象嘛(个人理解)
但是这种使用方式只能是一个参数或者0个参数的时候可以使用(参数是number)

//这样子是不行的
def lazyGString = "value == ${w -> w=number }"


和java互相通用性

GString都会默认调用toString();

String takeString(String message) {         
    assert message instanceof String        
    return message
}

def message = "The message is ${'hello'}"   
assert message instanceof GString          
//这里的message是被隐试调用toString()
def result = takeString(message)
 
assert result instanceof Stringassert result == 'The message is hello'

string的hashcodes和gString的hashcodes是不一样的,原因在于插值,即便插值前后的字符串是一样的,但是hashcodes还是不一样的。

def key = "a"
def m = ["${key}": "letter ${key}"]     

assert m["a"] == null     //这里就是不能通过a作为key得到值 
三个引号的字符串

类似于两个引号的字符串,在多行方面又类似于三个单引号的字符串

def name = 'Groovy'
def template = """
    Dear Mr ${name},

    You're the winner of the lottery!

    Yours sincerly,

    Dave
"""

assert template.toString().contains('Groovy')


除了引号的字符串,还有/字符串/的形式,这种形式在正则表达式方面比较有用

def fooPattern = /.*foo.*/
assert fooPattern == '.*foo.*'

/这个要转移一下
def escapeSlash = /The character \/ is a forward slash/
assert escapeSlash == 'The character / is a forward slash'
多行 的时候

def multilineSlashy = /one
    two
    three/

assert multilineSlashy.contains('\n')

同样支持插值
def color = 'blue'
def interpolatedSlashy = /a ${color} car/

assert interpolatedSlashy == 'a blue car'

但是不支持 //==""

assert '' == // 是错误的 编译器无法识别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值