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

查看:30
本文介绍了“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?

推荐答案

consts 是编译时常量.这意味着它们的值必须在编译时分配,不像 vals,它可以在运行时完成.

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天全站免登陆