zoukankan      html  css  js  c++  java
  • Groovy User Guide

    1. http://groovy.codehaus.org/User+Guide
    2. Control Structures
      1. Logical Branching
        1. if-else statement
          1. Groovy supports the usual if - else syntax from Java
            def x = false
            def y = false
            
            if ( !x ) {
                x = true
            }
            
            assert x == true
            
            if ( x ) {
                x = false
            } else {
                y = true
            }
            
            assert x == y
            
          2. Groovy also supports the normal Java "nested" if then else if syntax:

            if ( ... ) {
            ...
            } else if (...) {
            ...
            } else {
            ...
            }
            
        2. ternary operator
          def y = 5
          def x = (y > 1) ? "worked" : "failed"
          assert x == "worked"
          
        3. switch statement
          def x = 1.23
          def result = ""
          
          switch ( x ) {
              case "foo":
                  result = "found foo"
                  // lets fall through
          
              case "bar":
                  result += "bar"
          
              case [4, 5, 6, 'inList']:
                  result = "list"
                  break
          
              case 12..30:
                  result = "range"
                  break
          
              case Integer:
                  result = "integer"
                  break
          
              case Number:
                  result = "number"
                  break
          
              default:
                  result = "default"
          }
          
          assert result == "number"
          
      2. Looping
        1. while {...} loops

          def x = 0
          def y = 5
          while(y-->0){
              x++
          }
          assert x==5
          
        2. for loop

          //standard java for loop
          for(int i=0;i<5;i++){}
          //iterate over a range
          def x = 0
          for(i in 0..9){
              x += i
          }
          assert x==45
          //iterate over a list
          x = 0
          for(i in [0,1,2,3,4]){
              x+=i
          }
          assert x==10
          //iterate over an array
          array = (0..4).toArray()
          x = 0
          for(i in array){
              x+=i
          }
          assert x==10
          //iterate over a map
          def map = ['abc':1,'def':2,'xyz':3]
          x = 0
          for(e in map){
              x+=e.value
          }
          assert x==6
          //iterate over values in a map
          x = 0
          for(v in map.values()){
              x += v
          }
          assert x==6
          //iterate over the characters in a string
          def text = "abc"
          def list = []
          for(c in text){
              list.add(c)
          }
          assert list == ["a","b","c"]
          
        3. closures

          def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
                             "groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];
          
          def stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",
                            "We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday",
                            "Sa" : "Saturday" ];
          
          stringList.each() { print " ${it}" }; println "";
          
          stringMap.each() { key, value -> println "${key} --> ${value}" };
          
          stringList.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };
          
          stringMap.eachWithIndex() { obj, i -> println " ${i}: ${obj}" };
          
      3. Returning values from if-else and try-catch blocks
        def method() {
            if (true) 1 else 0
        }
        assert method() == 1
        
        def method(bool) {
            try {
                if (bool) throw new Exception("foo")
                1
            } catch(e) {
                2
            } finally {
                3
            }
        }
        assert method(false) == 1
        assert method(true) == 2
        
    3. Operators
      1. Arithmetic and Conditional Operators
        def expression = false
        assert !expression
        
      2. Collection-based Operators
      3. Spread Operator(*.)
        parent*.action                             //equivalent to:
        parent.collect{ child -> child?.action }
        
        assert ['cat', 'elephant']*.size() == [3, 8]
        
      4. Object-Related Operators
            invokeMethod and get/setProperty (.)
            Java field (.@)
            The spread java field (*.@)
            Method Reference (.&)
            'as' - "manual coercion" - asType(t) method
            Groovy == ( equals()) behavior.
                "is" for identity
            The instanceof operator (as in Java)
      5. Java field(.@)
      6. Other Operators
            getAt(index) and putAt(index, value) for the subscript operator (e.g. foo[1] or foo['bar'], i.e. index is either an int or String)
            Range Operator (..) - see Collections#Collections-Ranges
            isCase() for the membership operator (in)
      7. Elvis Operator(?:)
        def displayName = user.name ? user.name : "Anonymous" //traditional ternary operator usage
        
        def displayName = user.name ?: "Anonymous"  // more compact Elvis operator - does same as above
        
      8. Safe Navigation Operator(?.)
        def user = User.find( "admin" )           //this might be null if 'admin' does not exist
        def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown
        
      9. Regular Expression Operators
            find (=~)
            match (==~)
        
      10. Table of Operators

        Operator Name

        Symbol

        Description

        Spaceship

        <=>

        Useful in comparisons, returns -1 if left is smaller 0 if == to right or 1 if greater than the right

        Regex find

        =~

        Find with a regular expresion? See Regular Expressions

        Regex match

        ==~

        Get a match via a regex? See Regular Expressions

        Java Field Override

        .@

        Can be used to override generated properties to provide access to a field

        Spread

        *.

        Used to invoke an action on all items of an aggregate object

        Spread Java Field

        *.@

        Amalgamation of the above two

        Method Reference

        .&

        Get a reference to a method, can be useful for creating closures from methods

        asType Operator

        as

        Used for groovy casting, coercing one type to another.

        Membership Operator

        in

        Can be used as replacement for collection.contains()

        Identity Operator

        is

        Identity check. Since == is overridden in Groovy with the meaning of equality we need some fallback to check for object identity.

        Safe Navigation

        ?.

        returns nulls instead of throwing NullPointerExceptions

        Elvis Operator

        ?:

        Shorter ternary operator

    4. Bitwise Operations

      Operator Symbol

      Meaning

      <<

      Bitwise Left Shift Operator

      >>

      Bitwise Right Shift Operator

      >>>

      Bitwise Unsigned Right Shift Operator

      |

      Bitwise Or Operator

      &

      Bitwise And Operator

      ^

      Bitwise Xor Operator

      ~

      Bitwise Negation Operator

      <<=

      Bitwise Left Shift Assign Operator

      >>=

      Bitwise Right Shift Assign Operator

      >>>=

      Bitwise Unsigned Right Shift Assign Operator

      |=

      Bitwise Or Assign Operator

      &=

      Bitwise And Assign Operator

      ^=

      Bitwise Xor Operator

    5. Scripts and Classes

    6. Statements Add comment to Wiki

    7. Reserved Words

    8. Strings and GString

    9. http://groovy.codehaus.org/User+Guide
  • 相关阅读:
    如何将CentOS的默认启动界面修改为图形界面or字符界面
    如何将CentOS的默认启动界面修改为图形界面or字符界面
    virtualbox下CentOS7安装增强功能
    蓝牙4.0
    HC-SR04超声波测距
    STM32F407 通用同步异步收发器(串口)
    STM32F4 TIM(外设定时器)
    STM32F4 系统定时器
    STM32F4 异常与中断
    LED和按键实验
  • 原文地址:https://www.cnblogs.com/dmdj/p/3405279.html
Copyright © 2011-2022 走看看