26 Temmuz 2021 Pazartesi

Kotlin data Class

Giriş
Üye alanlar için getter(), setter(), equals(), hashCode() ve copy() metodları üretir. Açıklaması şöyle
1. data class cannot be abstract, inner, open or sealed.
2. At least 1 parameter is required in the primary constructor.
3. data class does not implement Serializable by default.
4. data class can implement interfaces and extend other classes (since v1.1).
Örnek
Şöyle yaparız
enum class RequestType {CREATE, DELETE}
data class RuleChange(val organizationId: String, val userIds: List<String>,
val request: RequestType)
Örnek
Açıklaması şöyle
If we want to exclude any property from being included in the automatically generated functions, we can put the property in the class body :

Only genre and artist properties will be used in the implementation of hashcode(), equal(), copy(), toString() method.
Şöyle yaparız
data class Song(val genre: String, val artist: String){
  var title: String;
}
val songA: Song = Song("Pop", "Jamie")
val songB: Song = Song("Pop", "Jamie")
songA.title = "Take the train"
songB.title = "All blues"
songA.equals(songB) // true
copy
Şöyle yaparız
val song: Song = Song("Jazz", "John")
val anotherSong: Song = song.copy()

print(song == anotherSong) // true
print(song === anotherSong) // false

val nextSong: Song = song.copy(artist = "Judy")

Hiç yorum yok:

Yorum Gönder