“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屋!