Groovy – String, StringBuffer, operator <<

Groovy 有一個通常用在 collection, map 等物件的 operator:  ‘<<‘, 其實也可以用在 String 上面, 像這樣:

def str = 'Groovy'
def str2 = str << ' is good.'
println str2    // => Groovy is good.

上例是 Groovy 簡化語法的成果, 因此在裡面可是暗藏玄機:

def str = 'Groovy'
def str2 = str << ' is good'
assert str2 != 'Groovy is good'
assert str2.toString() == 'Groovy is good'

上面我們可以看到 str2 並不等於 str, 一定要呼叫 toString() 才會相等.

再看下面的例子我們就可以看到答案了:

def myString1 = new StringBuilder("Groovy")
def myString2 = "Groovy"
println myString1.getClass().name
println myString2.getClass().name

println "--- result 1 ---"
def result1 = myString1 << " is good"
println result1.getClass().name
println result1

println "--- result 2 ---"
def result2 = myString2 << " is good"
println result2.getClass().name
println result2

結果如下:

java.lang.StringBuilder
java.lang.String
--- result 1 ---
java.lang.StringBuilder
Groovy is good
--- result 2 ---
java.lang.StringBuffer
Groovy is good

myString2 一開始只是普通的 String, 在使用過 << 後, 就被偷偷換成了 StringBuffer.
而另外一個 myString1 至終都是 StringBudiler, 未被更換.
因此可以推論若我們要在 String 上使用 <<, Groovy 在會視為要使用 StringBuffer, 而做自動轉換.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s