Smart cast to ‘TextView!‘ is impossible, because ‘txt‘ is a mutable property

初学kotlin后写了个android demo,但是TextView类型变量txt却提示Smart cast to 'TextView!' is impossible, because 'txt' is a mutable property that could have been changed by this time.

定义全局变量

private var txt: TextView?=null

onCreate方法中初始化

txt=findViewById(R.id.txt)
txt.setOnClickListener { Toast.makeText(this,"This is first kotlin demo",Toast.LENGTH_SHORT).show() }   

查阅资料发现是由于kotlin安全策略,因为txt是变量可能会改变,那么txt有可能为null,所以有了上面的提示。

所以该问题可以将txt设置为了常量,也可以先判断不为空再调用。

解决办法一,使用?先判断不为空再调用

txt?.setOnClickListener { Toast.makeText(this,"This is first kotlin demo",Toast.LENGTH_SHORT).show() }

解决办法二,将txt设置为常量,采用进行赋值初始化

        val txt: TextView=findViewById(R.id.txt)
        txt.setOnClickListener { Toast.makeText(this,"This is first kotlin demo",Toast.LENGTH_SHORT).show() }

解决办法三,定义全局变量时设置延时初始化

private lateinit var txt: TextView

kotlin和java还有一个函数区别是默认参数列表都是常量,所以不用再去申明val,更不能声明为var,否则就会报var on function paramter is not allowed

猜你喜欢

转载自blog.csdn.net/u013795543/article/details/113801264
今日推荐