问题描述
如果我们知道数据类型并且它不会在运行时更改,我们是否应该或者不应该定义方法的变量或返回类型的数据类型?有什么优点和缺点,或者使用def vs实际数据类型?
一个例子是,如果abc打算是
但到处使用 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具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!