7 数据类型

1       数据类型

1.1  弱类型变量

变量(Variables)和成员变量(fields)的定义,可以使用java中相应的强制类型,或者也可以使用def关键字来定义。一般来说,如果知道变量类型甚至该类型始终不变则使用强制类型,否则使用def。

// valid variable definitions
 
// typed
String name
int x
Integer y
 
// untyped
def list
def map
def todo 

运行时变量和成员变量总是强制类型的,这意味着,在运行时,如果你使用一个不合适的变量类型时,会报错。

在Groovy脚本中,没有被声明的变量可以被使用,这意味着这些变量能被在外部设置。

1.2  泛型

Groovy支持泛型,但是不会被强制。例如,你能放入任何类型到List<Integer>集合中。Groovy中,强制类型检查可以使用AST变形。看Section 22, “Compile-time meta programming and AST transformations”来学习更多的关于AST变形。

1.3  所有类型都是对象(objects)

Groovy中,所有变量都是对象(引用变量),Groovy不会使用原始类型的变量。Groovy允许你声明的时候可以使用原始类型的变量,如int,short,但是编译器会翻译成对象(object)。

1.4  数值型(Numbers)

在Groovy中,数值也是对象,例如:int,float,double等。

times 方法会执行{}里的代码指定的次数。

package first

 

class TypesTest {

   

    static main(args) {

       int i=1 //短形式的,等同于Integer i = new Integer(1)

       int j= i+3

       int k=i.plus(3)//与i+3相同

       assert(k==4)

       println i.class

       println j.class

       println k.class

      

       //自动分配类型

       def value = 1.0F

       println value.class

       def value2 = 1

       println value2.class

       //以下如果在java中,将会输出0,但是在Groovy中却输出0.5

       value2 = value2/2

       assert(value2== 0.5)

       println value2.class

       println("====================times")

       4.times {println "Test"}

    }

 

}

输出:

发现,4.times {println "Test"},会打印出4个Test,相当于for循环。

The operators, like + or - are also mapped to methods by Groovy.

操作符,像+或-,在Groovy中也被映射成了方法。

Table 1. 

Operator

Name

Method

a+b

plus

a.plus(b)

a-b

minus

a.minus(b)

a*b

star

a.multiply(b)

a/b

divide

a.div(b)

a%b

modulo

a.mod(b)

a--, --a

decrement

a.previous()

a++, ++a

increment

a.next()

a**b

power

a.power(b)

1.5  区间(Ranges)

Groovy支持Range 数据类型,其实就是一个Collection。被2个点,分割。例如下边的循环:

package first

 

class RangesTest {

 

    static main(args) {

       for (i in 0..3) {

           println ("Hello $i")

       }

       assert 'B'..'E'==['B', 'C', 'D', 'E']

    }

 

}

输出

你可以使用Strings来定义ranges,这些ranges是字母表。每个对象都可以使用Range ,其实现了previous() and next()方法以及java.util.Comparable接口。这2个方法分别映射为++和—操作。

原文地址:https://www.cnblogs.com/yaoyuan2/p/5708960.html