1.关于 ? 可为空的使用
(1)? 加在变量声明的类型参数后面表示该变量可为空,不加表示该变量不允许为空(kotlin默认),例如:
var name: String? = null
fun postName(name: String?) {
}
如果不加 ? 直接赋值为空或调用方法时传空则编译不通过。
(2)踩坑,从A页面打开B页面并传值 title,B页面接收参数代码如下
var title: String = intent.getStringExtra("title")
tv_title?.text = title
第一行代码intent.getStringExtra("title")的返回值可为空,但是变量声明时未加 ? 既表示不能为空,但是这里编译通过了(AS 3.4,KT 1.3.11),原因未知
运行的时候从A页面未传 title 打开B页面,直接崩溃切没有日志打印,日志如下:
05-14 11:04:24.006 D/Interception( 616): result: allow, reason: callerPkg == calleePkg, rule: runType===activity|||callerPkg===com.hyc.xhhelper|||calleePkg===com.hyc.xhhelper|||calleeClass===com.hyk.healthhome.view.activity.MeetingDetailActivityNew|||action===null
05-14 11:04:24.006 I/ActivityManager( 616): START u0 {cmp=com.hyc.xhhelper/com.hyk.healthhome.view.activity.MeetingDetailActivityNew (has extras)} from uid 10040 on display 0 ///////////////这里打开B页面
05-14 11:04:24.045 I/AppCompatDelegate( 7716): The Activity's LayoutInflater already has a Factory installed so we can not install AppCompat's
05-14 11:04:24.046 D/AndroidAutoSize( 7716): com.hyk.healthhome.view.activity.MeetingDetailActivityNew used the global configuration.
05-14 11:04:24.046 D/AndroidAutoSize( 7716): The com.hyk.healthhome.view.activity.MeetingDetailActivityNew has been adapted!
05-14 11:04:24.046 D/AndroidAutoSize( 7716): MeetingDetailActivityNew Info: isBaseOnWidth = true, designWidthInDp = 640.000000, designWidthInSubunits = 640.000000, targetDensity = 1.750000, targetScaledDensity = 1.750000, targetDensityDpi = 280, targetXdpi = 1.750000
05-14 11:04:24.067 D/AndroidRuntime( 7716): Shutting down VM /////////////这里直接崩溃
05-14 11:04:24.074 I/art ( 7716): Debugger is no longer active
解决:在声明时声明可为空
var title: String? = intent.getStringExtra("title")
tv_title?.text = title
在使用Gson时,Bean(kt)属性同样没用 ? 声明,后台返回为null时,依然可以运行通过,但是在使用时如果不用 ?. 或 !!. 同样崩溃且没有日志,直接是Shutdow vm
网友评论