"const"和"const"之间有什么区别?和"val"? [英] What is the difference between "const" and "val"?
问题描述
我最近读过有关const
关键字的信息,我很困惑!我找不到const
和val
关键字之间的任何区别,我的意思是我们可以同时使用它们来创建一个不可变的变量,我还有什么想念的吗?
I have recently read about the const
keyword, and I'm so confused! I can't find any difference between const
and the val
keyword, I mean we can use both of them to make an immutable variable, is there anything else that I'm missing?
推荐答案
const
s是编译时间常数.这意味着它们的值必须在编译时分配,这与val
s不同,后者可以在运行时完成.
const
s are compile time constants. Meaning that their value has to be assigned during compile time, unlike val
s, where it can be done at runtime.
这意味着,const
永远不能分配给函数或任何类构造函数,而只能分配给String
或基元.
This means, that const
s can never be assigned to a function or any class constructor, but only to a String
or primitive.
例如:
const val foo = complexFunctionCall() //Not okay
val fooVal = complexFunctionCall() //Okay
const val bar = "Hello world" //Also okay
这篇关于"const"和"const"之间有什么区别?和"val"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!