groovy 速学 - 02 - 数据类型与作用域

来源:互联网 发布:淘宝骗局 退款 礼品券 编辑:程序博客网 时间:2024/05/16 15:20

目录

    • 数据类型与作用域
      • 一切皆对象
      • 数据类型
        • 数字类型
        • 字符串
          • 概述
          • 常用方法
      • 类型推断
      • 动态类型与静态类型
    • 作用域
      • Groovy 类
      • Groovy 脚本

摘要

times(),upto(),downto(),step(),GString,类型转换,类型推断,作用域

数据类型与作用域

一切皆对象

Groovy 中一切皆对象,这意味着 Groovy 中不存在基本类型。

int i = 1def j = 2println i.class //class java.lang.Integerprintln j.class //class java.lang.Integer

可以看到在 Groovy 中基本类型实际是通过包装类实现的。

数据类型

数字类型

常用方法

  • n.times{} 执行 n 次
  • n.upto(m){} 执行 m-n+1 次
  • n.downto(m){} 执行 n-m+1 次
  • n.step(a,b){} 执行 (a-n)b 次,即从 n 开始,每次步长 b,直到等于 a
def store = ""10.times { store += "x" }assert store == "xxxxxxxxxx"store = ""1.upto(5) { n -> store += n }assert store == "12345"store = ""2.downto(-2) { n -> store += n + "" }assert store == "210-1-2"store = ""0.step(0.5, 0.1) { n -> store += n + "," }assert store == "0,0.1,0.2,0.3,0.4,"

A:

可以用来代替 for 循环

字符串

概述

Groovy 中可以使用 Java 的 String 和 Groovy 的 GString 表示字符串。

原则

  • 当没有明确指明类型时,字符串都会被推断为 String 类型
  • String 可以用单引号或双引号声明,但是 GString 只能以双引号声明
  • 只有 GString 支持使用引用符 ${}
  • 三引号 """''' 可以定义跨行的字符串,即按格式原样输出
  • 双引号内部可以使用单引号,单引号内部可以使用双引号
def x = 2def singleQuote = 'abc'def doubleQuotes = "abc"def singleQuote2 = 'abc${x}'def doubleQuotes2 = "abc${x}"println singleQuote.class   //class java.lang.Stringprintln doubleQuotes.class  //class java.lang.Stringprintln singleQuote2.class  //class java.lang.Stringprintln doubleQuotes2.class //class org.codehaus.groovy.runtime.GStringImplprintln singleQuote2        //abc${x}println doubleQuotes2       //abc2

A:

尽量使用 GString 进行字符串拼接

常用方法
def str = 'Groovy&Grails&lxt008'println str[4]                  //vprintln str[-1]                 //8println str[1..2]               //roprintln str[1..<3]              //roprintln str[4, 1, 6]            //vr&println 'a' == 'a'              //trueprintln 'a' <=> 'a'             //0println 'a'.compareTo('a')      //0println 'a' - 'a'               //println 'a' + 'a'               //aaprintln 'a' * 3                 //aaastr = 'Groovy'println str.center(11)          //  Groovyprintln str.center(2)           //Groovyprintln str.center(11, '=')     //==Groovy===println str.count('o')          //2println str.leftShift(' world') //Groovy worldprintln str << ' world'         //Groovy worldprintln str.minus('vy')         //Grooprintln str - 'vy'              //Grooprintln str.next()              //Groovzprintln str.previous()          //Groovxprintln str.padLeft(4)          //Groovyprintln str.padLeft(11)         //     Groovyprintln str.padLeft(11, "=")    //=====Groovyprintln str.replaceAll('[a-z]') { ch -> ch.toUpperCase() }  //GROOVYprintln '123'.toDouble()                                    //123.0println '123'.toList()                                      //[1, 2, 3]//tokenize 返回 List,split 返回数组str = "Groovy Grails&lxt"println str.tokenize()                                      //[Groovy, Grails&lxt]println str.tokenize('&')                                   //[Groovy Grails, lxt]println str.tokenize().getClass().getName()                 //java.util.ArrayListprintln str.tokenize("t").getClass().getName()              //java.util.ArrayListprintln str.split("t").getClass().getName()                 //[Ljava.lang.String;

A:

使用 toDouble()等进行类型转换

类型推断

在 Java 中以下代码代表一个 String

String value = "Hello World";

但是实际上从 “=” 右边就可以推断出这是一个 String,左边的类型声明有点多此一举。所以 Groovy 允许使用 def 定义变量,具体类型由 Groovy 根据右边的值进行推断。如果 Groovy 无法推断具体的类型则会把它当做是 Object。

def value = "Hello World"

可以通过调用 .class 来查看变量的具体类型

println value.class

因为 Groovy 是无类型的,所以方法中的参数也可以 省略 def 关键字

A:

除非必要,使用 def 定义变量

动态类型与静态类型

Groovy 支持动态类型和静态类型

动态类型

def dynamicDate = new Date()

静态类型

Date staticDate = new Date()

如果声明了静态类型,就不能再改变该变量的类型

作用域

Groovy 类

Groovy 类作用域同 Java

Groovy 脚本

绑定域:脚本内的全局作用域,相当于该脚本对象的成员变量。如果没有定义过变量(可以直接使用或仅仅初始化但未声明),其作用域即是绑定域。
本地域:脚本内的代码块。如果是定义过的变量,其作用域就是本地域。

脚本中声明的方法访问不了本地域

String hello = "hello"  //定义变量,作用域是本地域def world = "world"     //定义变量,作用域是本地域helloworld = "hello world"  //全局变量,作用域是绑定域void check() {    println hello    println world    println helloworld}check()
0 0
原创粉丝点击