剛剛?cè)肓薻otlin的坑,對(duì)之前的base 庫(kù)進(jìn)行全面kotlin語(yǔ)言替換的時(shí)候出現(xiàn)了這個(gè)問(wèn)題秸滴。
問(wèn)題如下:
-- Smart cast is impossible, because 'phone' is a mutable property that could have been changed by this time
FE10F8FA3F9390316D4A954467947208.png
幾個(gè)意思呢?幌陕?
- 查了一下發(fā)現(xiàn)是因?yàn)閗otlin遵循的安全規(guī)則汹买,不允許向列表添加Nullable值,在別的線程可以對(duì)Nullable值phone做修改静暂,這樣在執(zhí)行phone.startsWith("+86")或者phone.substring(3)時(shí)它的值有可能為null济丘。
很好,有個(gè)性的語(yǔ)言
在這里,我這邊對(duì)于這個(gè)phone是這么定義的:
private var phone: String?=null
定義成var呢摹迷,是可以被改變的疟赊,那么接下來(lái)有兩種解決方案
1.使用val聲明可能會(huì)被變成null的nullable值,這樣nullable值就不可能被修改峡碉。
private val phone: String?=null
原本講道理是可以的近哟,如果你們不會(huì)對(duì)它再做出新的可變賦值的話
不過(guò)此處,我這邊的需求是不滿足的
A9EE0917F9603D27779F2D792003F93D.png
就是說(shuō)定義成val的話就不可以再次被修改
2.然后我換成了下面的解決方案:把nullable值賦值給一個(gè)新的變量鲫寄,然后再做其他操作
phone = tm.line1Number
val p = phone
if(p != null) {
if (!TextUtils.isEmpty(phone) && p.startsWith("+86")) {
phone = p.substring(3)
}
}
然后解決之后的樣子是這樣的:
private fun checkTelecomInfo(context: Context) {
try {
val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
IMEI = tm.deviceId
IMSI = tm.subscriberId
phone = tm.line1Number
val p = phone
if(p != null) {
if (!TextUtils.isEmpty(phone) && p.startsWith("+86")) {
phone = p.substring(3)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
希望對(duì)入坑Kotlin吉执,不小心踩坑的你有幫助