Groovy: keyword "def" versus concrete type

Should we or should not indicate the data type of the variable or the type of the returned method, if we know the data type, and also it will not change at run time? What are the pros and cons or using def vs actual datatype?

One example: if abc should be List<String>

List<String> abc = "xyz"; //IntelliJ IDEA gives syntax highlighting for improper assignment
def abc = "xyz"; //IntelliJ IDEA will not give syntax highlighting
+4
source share
2 answers

It's easy to fall into the trap of use defeverywhere, because of convenience (especially if you come with Java)

But, as you saw, if you know the type of something, it is better to type it, especially on public methods. Benefits include; independent documentation, ideological hints, sanity ...

+6
source

def ~ = Object

, def - Object, (Object , def a Groovy) - http://www.groovy-lang.org/semantics.html#_variable_definition , def Object, , JVM def Object,

test.groovy script :

def name = "John"

String surname = "Doe"

println "$name $surname"

test.class , :

Compiled from "test.groovy"
public class test extends groovy.lang.Script {
  public static transient boolean __$stMC;

  public test();
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          4       4     0  this   Ltest;

  public test(groovy.lang.Binding);
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0       9     0  this   Ltest;
          0       9     1 context   Lgroovy/lang/Binding;

  public static void main(java.lang.String...);
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0      19     0  args   [Ljava/lang/String;

  public java.lang.Object run();
    LineNumberTable:
      line 1: 4
      line 3: 9
      line 5: 14
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0      63     0  this   Ltest;
          7      56     2  name   Ljava/lang/Object;
         12      51     3 surname   Ljava/lang/String;

  protected groovy.lang.MetaClass $getStaticMetaClass();
}

IDE

IDE, Groovy (, IntelliJ IDEA), , IDE .

def

def Groovy. , Java Object.

, . API . def :

  • , ,
  • Spock unit , . def "should do something"() { }
+5

Source: https://habr.com/ru/post/1662048/


All Articles