用'def'声明变量并用已知类型声明它有什么区别? [英] Is there any difference between declaring a variable with 'def' and declaring it with a known type?

查看:337
本文介绍了用'def'声明变量并用已知类型声明它有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个定义的类

  class MyClass {
}

是否在运行时在执行 def c = new MyClass()而不是 MyClass c = new MyClass()?或者它是完全一样的?

解决方案

def 类型名称。在变量定义中,它用来表示你不关心这个类型。



如果你没有声明变量的类型,那么Groovy将会被隐藏声明为类型 Object 。您可以将 def 视为 Object 的别名。



在你的例子中:

  def c = new MyClass()
//转换为:
java.lang.Object c = new MyClass()






<$ $ b $ MyClass c = new MyClass()
//转换为:
MyClass c = new MyClass()


Assuming I have a defined class

class MyClass {
}

Is there a hit in performance in runtime in doing def c = new MyClass() instead of MyClass c = new MyClass()? Or is it exactly the same?

解决方案

def is a replacement for a type name. In variable definitions it is used to indicate that you don't care about the type.

If you don't declare the type of variable, Groovy under the covers will be declared as type Object. You can think of def as an alias of Object.

In your example:

def c = new MyClass()
// transform to:
java.lang.Object c = new MyClass()


MyClass c = new MyClass()
// transform to:
MyClass c = new MyClass()

这篇关于用'def'声明变量并用已知类型声明它有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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