groovy与java比较

默认导入以下包

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*
  • groovy.lang.*
  • groovy.util.*

常见错误

  • ==代表equals()
  • in是一个关键字
  • 声明数组用[ ]
  • for (int i=0; i < len; i++) {...}一般用以下简写
    • for (i in 0..len-1) {...}
    • for (i in 0..<len) {...}
    • len.times {...}

注意事项

  • 分号是可选的多条语句写在一行时必须用分号
  • return关键字是可选的
  • static methods内必须使用this关键字
  • 方法和类默认是pubilc
  • protected同java
  • 不支持内部类,可用闭包(closures)代替
  • 不会检查方法throws的异常,there is no difference between checked and unchecked exceptions.
  • 没有定义的成员和类型不编译是不会报错,参见Runtime vs Compile time, Static vs Dynamic.

New features added to Groovy not available in Java

  • Closures
  • native syntax for lists and maps
  • GroovyMarkup and GPath support
  • native support for regular expressions
  • polymorphic iteration and powerful switch statement
  • dynamic and static typing is supported - so you can omit the type declarations on methods, fields and variables
  • you can embed expressions inside strings
  • lots of new helper methods added to the JDK
  • simpler syntax for writing beans for both properties and adding event listeners
  • safe navigation using the ?. operator, e.g. "variable?.field" and "variable?.method()" - no more nested ifs to check for null clogging up your code

你可能感兴趣的:(groovy)