Hi I am making a app with Kotlin and I found that I can both use
textView.setText(str)
and
textView.text =
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
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(str)
and textView.text = $str
, does the same job of setting the specified str
to TextView
. The only difference I can come up with is,
textView.setText(str) // old Java way of setting Text
where method setText(str) was being called.
textView.text = $str //new Kotlin way of setting Text
where instead of a method, a synthetic property is being called.
As in the Kotlin, you are not using findViewById
so to access your textView, import statement must be like this
import kotlinx.android.synthetic.main.<layout>.*
And textView.text = $str
is the Synthetic Property access provided by Kotlin Plugin for android
You can use both, not much difference in the usability, but for the easier code writing this would be better
For more information, read this https://kotlinlang.org/docs/tutorials/android-plugin.html
Both works the same way.
Java Convention
textView.setText(“…”)
Kotlin Convention
textView.text=”…”
“Methods that follow the Java conventions for getters and setters (no-argument methods with names starting with get and single-argument methods with names starting with set) are represented as properties in Kotlin.”- documentation
thus textView.text=”…”
instead of textView.setText(“…”)
if you are using Kotlin to follow Kotlin Conventions.
Ref - Begin Kotlin; from an Activity, a Button and a TextView
The method setText()
and getText()
are called setters and getters, they are automatically generated in kotlin.
class ClassName{
var name: String= "some_value"
}
You can use the name
property directly with the object of the class or you can also use the auto-generated setter
method.
class Another{
var c = ClassName()
c.name = "value"
c.setName("value")
}
But if a property starts with a val
instead of var
then it is immutable and does not allow a setter
.
In case you want to read further:-
Setters and getters in kotlin