groovy-真值
2013-10-02 01:32 Rollen Holt 阅读(569) 评论(0) 编辑 收藏 举报Boolean expressions
Groovy支持标准的条件运算符的布尔表达式:
1 |
def a = true |
2 |
def b = true |
3 |
def c = false |
4 |
assert a |
5 |
assert a && b |
6 |
assert a || c |
7 |
assert !c |
此外,Groovy中有强制转换非布尔对象为布尔值的特殊规则。
集合
空集合会被强制转换为false:
1 |
def numbers = [ 1 , 2 , 3 ] |
2 |
assert numbers //true, as numbers in not empty |
3 |
numbers = [] |
4 |
assert !numbers //true, as numbers is now an empty collection |
迭代器和枚举
没有进一步元素的枚举和迭代器都会被强制转换为false:
1 |
assert ![].iterator() // false because the Iterator is empty |
2 |
assert [ 0 ].iterator() // true because the Iterator has a next element |
3 |
def v = new Vector() |
4 |
assert !v.elements() // false because the Enumeration is empty |
5 |
v.add( new Object()) |
6 |
assert v.elements() // true because the Enumeration has more elements |
Map
非空的map被强制转换为true:
1 |
assert [ 'one' : 1 ] |
2 |
assert ![:] |
Matchers
当匹配到正则表达式的模式的时候会强制转换为true:
1 |
assert ( 'Hello World' =~ /World/) //true because matcher has at least one match |
Strings
非空的Strings, GStrings 和CharSequences 将被强制转换为true:
1 |
<div> |
2 |
<div> |
3 |
<pre><code data-result= "[object Object]" > // Strings |
4 |
assert 'This is true' |
5 |
assert ! '' |
6 |
//GStrings |
7 |
def s = '' |
8 |
assert !( "$s" ) |
9 |
s = 'x' |
10 |
assert ( "$s" ) |
Numbers
非0的数值被强制转换为true,就如同perl一样。
1 |
<div> |
2 |
<div> |
3 |
<pre><code data-result= "[object Object]" > assert ! 0 //yeah, 0s are false, like in Perl |
4 |
assert 1 //this is also true for all other number types |
Object references
非null的对象引用被强制转换为true:
1 |
assert new Object() |
2 |
assert ! null |
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================