作者:搜狐搜不到你的爱_276 | 来源:互联网 | 2023-12-12 17:06
在Java中,我会做这样的事情:classPerson{privateRecordrecord;publicStringname(){record().get(name);}p
在Java中,我会做这样的事情:
class Person {
private Record record;
public String name() {
record().get("name");
}
private Record record() {
if (record == null) {
refetch();
}
return record;
}
private void refetch() {
record = service.doSomething()
}
}
在Kotlin,我有这个等价的代码:
class Person(private var record: Record?) {
fun name() : String {
record().get("name");
}
private fun record() : Record {
record ?: refetch()
return record!!;
}
private fun refetch() {
record = service.doSomething()
}
}
如你所见,我正在使用!!运算符,我真的不喜欢.还有另外一种惯用的方法吗?
如果我只是遵循Java方式(if(record == null)),我会收到此错误:
Smart cast to “Record” is impossible, because “record” is a mutable
property that could have been changed by this time
解决方法:
在惯用的Kotlin中,你会使用lazy delegated property:
class Person(private val service: Service) {
private val record by lazy { service.doSomething() }
fun name() = record.get("name");
}