kotlin 编译时常量_Kotlin程序| 编译时常量示例

kotlin 编译时常量

编译时常数 (Compile-time Constant)

  • If the value of a read-only (immutable) property is known at the compile time.

    如果在编译时已知只读(不可变)属性的值。

  • Mark it as a compile-time constant using the const modifier.

    使用const修饰符将其标记为编译时常量。

  • Such properties must be fulfilled by the following requirements.

    这些特性必须满足以下要求。

    • Top-level, or member of an object declaration or a companion object.
    • Initialized with a value of type String or a primitive type
    • No custom getter
  • No run time assignment allowed into const variables.

    不允许将运行时分配分配给const变量。

  • The val keyword also used to make property immutable but the main difference between const and val is that properties declare with val can be initialized at runtime.

    val关键字还用于使属性不可变,但是const和val之间的主要区别在于,可以在运行时初始化使用val声明的属性。

Kotlin中的编译时常数程序 (Program for compile-time constant in Kotlin)

package com.includehelp

//declare Top Level compile time constant
const val PI=3.14

//Declare Class with object to make singleton
object Physics{
    //declare compile time constant
    const val GRAVITY=10
}

//declare class
class Greetings{
    //declare companion object
    companion object{
        //declare compile time constant
        const val GREET="Hello IncludeHelp"
    }
}

//Main Function, Entry Point of Program
fun main(){
    //Print All Constant Value
    println("PI Value : $PI")
    println("Gravity  : ${Physics.GRAVITY}")
    println("Greetings: ${Greetings.GREET}")
}

Output:

输出:

PI Value : 3.14
Gravity  : 10
Greetings: Hello IncludeHelp


翻译自: https://www.includehelp.com/kotlin/example-of-compile-time-constant.aspx

kotlin 编译时常量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值