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

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

问题描述

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

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?

一个例子是,如果 abc 是 List

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

推荐答案

很容易陷入使用 def 的陷阱,因为方便(特别是如果来自 Java)

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

但正如您所见,如果您知道某物的类型,最好输入它,尤其是在公共方法上.好处包括;自我文档、ide 提示、理智...

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:“定义"关键字与具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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