Groovy:“def”关键字vs具体类型 [英] Groovy: "def" keyword vs concrete type

查看:383
本文介绍了Groovy:“def”关键字vs具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们知道数据类型并且它不会在运行时更改,我们是否应该或者不应该定义方法的变量或返回类型的数据类型?有什么优点和缺点,或者使用def vs实际数据类型?



一个例子是,如果abc打算是 List< String> code>

 列表< String> abc =xyz; // IntelliJ IDEA为不恰当赋值赋予语法高亮
def abc =xyz; // IntelliJ IDEA不会给出语法高亮


解决方案

陷入陷阱,因为方便(特别是如果来自Java)

但到处使用 def 你已经看到了,如果你知道某种东西的类型,最好是输入它,特别是在公共方法上。好处包括;自我记录,ide提示,理智......


Should we or should we not define the datatype of a variable or return type of a method if we know the datatype and also it is not going to change at runtime? What are the pros and cons or using def vs actual datatype?

One example being, if abc is intended to 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

解决方案

It's easy to fall into the trap of using def everywhere, due to convenience (especially if coming from Java)

But as you have seen, if you know the type of something, it's better to type it, especially on public methods. Benefits include; self documentation, ide hints, sanity...

这篇关于Groovy:“def”关键字vs具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆