Kotlin for Android Developers
The key concept: just use
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
- Bu sahifa navigatsiya:
- 6.3 Properties
The key concept: just use
val as much as possible. There will be situations (specially in Android, where we don’t have access to the constructor of many classes) where it won’t be possible, but it will most of the time. Another thing mentioned before is that we usually don’t need to specify object types, they will be inferred from the value, which makes the code cleaner and faster to modify. We already have some examples from the section above. 1 val s = "Example" // A String 2 val i = 23 // An Int 3 val actionBar = supportActionBar // An ActionBar in an Activity context However, a type needs to be specified if we want to use a more generic type: 1 val a: Any = 23 2 val c: Context = activity 6.3 Properties Properties are the equivalent to fields in Java, but much more powerful. Properties will do the work of a field plus a getter plus a setter. Let’s see an example to compare the difference. This is the code required in Java to safely access and modify a field: 1 public class Person { 2 3 private String name; 4 5 public String getName() { 6 return name; 7 } 8 9 public void setName(String name) { 10 this.name = name; 6 Variables and properties 25 11 } 12 } 13 14 ... 15 16 Person person = new Person(); 17 person.setName("name"); 18 String name = person.getName(); In Kotlin, only a property is required: 1 public class Person { 2 3 var name: String = "" 4 5 } 6 7 ... 8 9 val person = Person() 10 person.name = "name" 11 val name = person.name If nothing is specified, the property uses the default getter and setter. It can, of course, be modified to run whatever custom code you need, without having to change the existing code: 1 public class Person { 2 3 var name: String = "" 4 get() = field.toUpperCase() 5 set(value) { 6 field = "Name: $value" 7 } 8 9 } If the property needs access to its own value in custom getter and setter (as in this case), it requires the creation of a backing field. It can be accessed by using field , a reserved word, and will be automatically created by the compiler when it finds that it’s being used. Take into account that if we used the property directly, we would be using the setter and getter, and not doing a direct assignment. The backing field can only be used inside property accessors. 6 Variables and properties 26 As mentioned in some previous chapters, when operating with Java code Kotlin will allow to use the property syntax where a getter and a setter are defined in Java. The compiler will just link to the original getters and setters, so there are no performance penalties when using these mapped properties. |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling