textView.setText(string)和textView.text = $ string有什么区别 [英] What is the difference between textView.setText(string) and textView.text = $string

查看:273
本文介绍了textView.setText(string)和textView.text = $ string有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Kotlin 制作应用程序,发现我俩都可以使用

Hi I am making a app with Kotlin and I found that I can both use

textView.setText(str)

textView.text = $str

我想知道我应该使用什么以及它们之间的区别. 谢谢.

I wanna know what I should use and the differences between them. Thank you.

推荐答案

在大多数情况下它们是相同的 ,基本上Kotlin会根据其getter为类属性生成一个综合属性,您可以可以用于向中分配值并从中获取值.

They're the same in most cases, basically Kotlin generates a synthetic property for the class attributes based on their getter, which you can use to assign values to and get values from.

//So, for most cases
textView.setText("some value");
//Is the same as
textView.text = "some value"
//The second is simply shorter and is the 'kotlin way' of assigning values

现在,这是要抓住的地方-

在大多数情况下,这可以正常工作.但是,如上所述,合成属性是从吸气剂生成的,如果也有一个setter,则会出现问题.原因是getter和setter的可能具有不同的类型.例如,EditText具有Editable吸气剂,现在,kotlin创建类型为Editable的合成属性text.

Now, here's the catch -

In most cases, this works fine. But, as mentioned, the synthetic property is generated from the getter, if there is a setter as well, then issues arise. The reason is that the getter and the setter may have different types. For example, EditText has Editable getter, now, kotlin creates a synthetic property text of the type Editable.

editText.setText("some value"); //Works
editText.text = "some value" //Won't work, will show an error stating that expected type is Editable

这篇关于textView.setText(string)和textView.text = $ string有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆