这取决于Java类的结构。

huangapple go评论69阅读模式
英文:

What does it depend on, whether you can or cannot call a Java getter/setter method using Kotlin's property access syntax, in one case or another?

问题

在某些情况下,您可以使用属性访问语法引用Java的getter/setter,而在另一些情况下则不能。是什么定义了这种行为?

val tv = TextView(this)
tv.setText("") // 弱警告:使用setter方法而不是属性访问语法
tv.text = "" // 正常

val iv = ImageView(this)
iv.setImageResource(R.drawable.ic_launcher_background) // 没有弱警告,可以使用这种方式
iv.imageResource = R.drawable.ic_launcher_background // 错误:未解析的引用:imageResource
英文:

In some cases you are able to use property access syntax to reference Java getters/setters, in some cases you aren't. What defines this behaviour?

val tv = TextView(this)
tv.setText("") // WEAK WARNING: Use of setter method instead of property access syntax
tv.text = "" // OK

val iv = ImageView(this)
iv.setImageResource(R.drawable.ic_launcher_background) // no weak warning, meant to be used that way
iv.imageResource = R.drawable.ic_launcher_background // ERROR: Unresolved reference: imageResource

这取决于Java类的结构。

答案1

得分: 3

只有在找到与之匹配的类型的getter和setter时,它才会创建属性。在你的ImageView示例中,有一个setImageReference但没有getImageReference,所以没有属性。

另一个例子是TextView。你可以这样做

textView.text = "hello"

但你不能这样做

textView.text = R.string.hello // 必须使用textView.setText(R.string.hello)

这是因为TextView.getText()返回一个CharSequence,所以唯一匹配的setText重载是接受CharSequence参数的那个。

英文:

It only creates a property if it can find a getter and setter with matching type. In your ImageView example, there's a setImageReference but no getImageReference, so no property.

Another example would be with TextView. You can do

textView.text = "hello"

but you cannot do

textView.text = R.string.hello // have to use textView.setText(R.string.hello)

This is because TextView.getText() returns a CharSequence so the only setText overload that matches is the one that takes a CharSequence argument.

答案2

得分: 2

Kotlin文档中得知:

>请注意,如果Java类只有setter,则在Kotlin中它不可见作为属性,因为Kotlin不支持仅具有setter的属性。

ImageView有一个setImageResource但没有getImageResource,因此它属于上述提到的情况。

英文:

From the Kotlin documentation:

>Note that, if the Java class only has a setter, it isn't visible as a property in Kotlin because Kotlin doesn't support set-only properties.

ImageView has a setImageResource but no getImageResource, so it falls into the category mentioned above.

huangapple
  • 本文由 发表于 2023年3月15日 20:38:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744826.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定