"const"和"const"之间有什么区别?和"val"? [英] What is the difference between "const" and "val"?

查看:118
本文介绍了"const"和"const"之间有什么区别?和"val"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近读过有关const关键字的信息,我很困惑!我找不到constval关键字之间的任何区别,我的意思是我们可以同时使用它们来创建一个不可变的变量,我还有什么想念的吗?

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不同,后者可以在运行时完成.

consts are compile time constants. Meaning that their value has to be assigned during compile time, unlike vals, where it can be done at runtime.

这意味着,const永远不能分配给函数或任何类构造函数,而只能分配给String或基元.

This means, that consts 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屋!

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