英文:
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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论