java 中的编译期常量_什么可以用编译时常量(const val)表示?

getter 不是方法调用,实际上,它是's a part of property declaration, for example, the code below can' t被编译 .

const val charFromString get() = "foo"

// ^--- const using getter can't be compiled

aComputedString 常量使用字符串模板,就像java中的字符串连接一样,例如:

static final String aComputedString = "Hello " + ((char) 0x57)

+ "orld" + ((char) ((1 << 5) | 1));

和opeartor针对原始类型进行了优化,因为它们在java中没有方法,例如:

const val longValue = 1.toLong();

// java

static final long longValue = (long) 1 ;

你的 comparedString 上面的代码可以工作的是你正在使用 kotlin.String 而不是 java.lang.String ,因为映射类型 kotlin.String 也是优化的,因为在kotlin中没有实现,如果你直接尝试 java.lang.String ,你可以获得预期的编译器错误:

typealias JavaString = java.lang.String;

// v--- error

const val comparedString = JavaString("Hello").compareTo("World!")

"Hello world!"[3] 无法正常工作,因为indexed access operator的参数类型是 vararg ,因此编译器可以知道 get 运算符将接收多少个参数,因此使用List列表动态调用它,例如:

const val third = "Hello world!"[3] //error

// will generate java code as

static final String third = "Hello world!".charAt(3) // error

但是,对于具有基本类型的固定参数的运算符,将由编译器进行优化:

请注意,这些操作以及所有其他操作都针对Basic类型进行了优化,并且不会为它们引入函数调用的开销 .

const val comparison = "Hello" > "World";// ok

String.get(n) 可以工作,因为 kotlin.String 是一个映射器类型,它没有实现,因此编译器知道如何计算它,例如:

const val third = "Hello".get(3) // ok

// ^

// when you calling the `get` function, you never using `operator` at all.

// it just a function invocation

String.toList() 无法分配给常量变量,因为它是一个扩展方法并且具有实现 . 和kotlin const val 只支持原始类型和字符串 .

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值