Kotlin의 게터 및 세터
예를 들어 Java에서는 getter를 직접 작성하거나 (IDE에서 생성) lombok에서 @Getter와 같은 주석을 사용할 수 있습니다. 매우 간단합니다.
그러나 Kotlin에는 기본적으로 getter 및 setter가 있습니다. 그러나 나는 그것들을 사용하는 방법을 이해할 수 없습니다.
나는 그것을 만들고 싶다. 자바와 비슷하다.
private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.
그렇다면 게터는 어떻게 작동합니까?
Getter 및 Setter는 Kotlin에서 자동 생성됩니다. 당신이 쓰는 경우 :
val isEmpty: Boolean
다음 Java 코드와 동일합니다.
private final Boolean isEmpty;
public Boolean isEmpty() {
return isEmpty;
}
귀하의 경우 개인 액세스 수정자는 중복입니다-isEmpty는 기본적으로 개인이며 getter에서만 액세스 할 수 있습니다. 객체의 isEmpty 속성을 얻으려고 할 때 실제로 get 메서드를 호출합니다. Kotlin의 게터 / 세터에 대한 더 많은 이해를 위해 아래 두 코드 샘플이 동일합니다.
var someProperty: String = "defaultValue"
과
var someProperty: String = "defaultValue"
get() = field
set(value) { field = value }
또한 this
getter에서 귀하의 속성이 아니라 클래스 인스턴스 라는 점을 지적하고 싶습니다 . getter 또는 setter에서 필드 값에 액세스하려면 예약어를 사용할 수 있습니다 field
.
val isEmpty: Boolean
get() = field
퍼블릭 액세스에서만 get 메서드를 사용하려는 경우 다음 코드를 작성할 수 있습니다.
var isEmpty: Boolean
private set
set 접근 자 근처의 private 한정자로 인해이 값은 개체 내부의 메서드에서만 설정할 수 있습니다.
속성 접근 자 가시성 수정 자 에 대한 규칙은 다음과 같습니다.
var
및val
속성 의 Getter 가시성은 속성의 가시성 과 정확히 동일 해야 하므로 속성 수정자를 명시 적으로 복제 만 할 수 있지만 중복됩니다.protected val x: Int protected get() = 0 // No need in `protected` here.
var
속성의 Setter 가시성은 속성 가시성과 동일하거나 덜 관대 해야합니다 .protected var x: Int get() = 0 private set(x: Int) { } // Only `private` and `protected` are allowed.
Kotlin에서 속성은 항상 getter 및 setter를 통해 액세스되므로 Java와 같은 접근자를 사용하여 속성 private
을 만들 필요가 없습니다. 지원 필드 (있는 경우) 는 이미 비공개입니다. 따라서 속성 접근 자에 대한 가시성 수정자는 setter 가시성을 덜 허용 적으로 만드는 데만 사용됩니다.public
지원 필드 및 기본 접근자가있는 속성의 경우 :
var x = 0 // `public` by default private set
지원 필드가없는 속성의 경우 :
var x: Int // `public` by default get() = 0 protected set(value: Int) { }
kotlin의 Getter는 기본적으로 public이지만 setter를 private으로 설정하고 클래스 내에서 하나의 메서드를 사용하여 값을 설정할 수 있습니다. 이렇게.
/**
* Created by leo on 17/06/17.*/
package foo
class Person() {
var name: String = "defaultValue"
private set
fun foo(bar: String) {
name = bar // name can be set here
}
}
fun main(args: Array<String>) {
var p = Person()
println("Name of the person is ${p.name}")
p.foo("Jhon Doe")
println("Name of the person is ${p.name}")
}
1) 예 기본 setter
및 getter
대한 재산 firstName
코 틀린에
class Person {
var firstName: String = ""
get() = field // field here ~ `this.firstName` in Java or normally `_firstName` is C#
set(value) {
field = value
}
}
사용
val p = Person()
p.firstName = "A" // access setter
println(p.firstName) // access getter (output:A)
IF your setter
or getter
is exactly same above, you can remove it because it is unnecessary
2) Example custom setter and getter.
const val PREFIX = "[ABC]"
class Person {
// set: if value set to first name have length < 1 => throw error else add prefix "ABC" to the name
// get: if name is not empty -> trim for remove whitespace and add '.' else return default name
var lastName: String = ""
get() {
if (!field.isEmpty()) {
return field.trim() + "."
}
return field
}
set(value) {
if (value.length > 1) {
field = PREFIX + value
} else {
throw IllegalArgumentException("Last name too short")
}
}
}
Using
val p = Person()
p.lastName = "DE " // input with many white space
println(p.lastName) // output:[ABC]DE.
p.lastName = "D" // IllegalArgumentException since name length < 1
More
I start learn Kotlin from Java so I am confusing about field
and property
because in Java there is no property
.
After some search, I see field
and property
in Kotlin look like C# (What is the difference between a field and a property?)
Here is some relevant post which talk about field
and property
in Java and Kotlin.
does java have something similar to C# properties?
https://blog.kotlin-academy.com/kotlin-programmer-dictionary-field-vs-property-30ab7ef70531
Correct me if I am wrong. Hope it help
You can see this tutorial for more info:
Yet Another Kotlin Tutorial for Android Developers
Properties
In Kotlin world, classes cannot have fields, just properties. var keyword tells us the property is mutable, in contrast to val. Let’s see an example:
class Contact(var number: String) { var firstName: String? = null var lastName: String? = null private val hasPrefix : Boolean get() = number.startsWith("+") }
There is not much code, but lots of things are happening behind the scenes. We will go through it step by step. First of all, we created a public final class Contact.
This is the primary rule we have to face: if not specified otherwise, classes are public and final by default (by the way, the same is for class methods). If you want to inherit from class, mark it with open keyword.
참고URL : https://stackoverflow.com/questions/37906607/getters-and-setters-in-kotlin
'program story' 카테고리의 다른 글
C ++ 헤더 파일에 구현이 어떻게 포함될 수 있습니까? (0) | 2020.12.07 |
---|---|
ADT 업데이트 후 ClassNotFoundException (0) | 2020.12.07 |
Mercurial 저장소 기록에서 삭제 된 파일을 신속하게 찾으십니까? (0) | 2020.12.07 |
Django 오류 메시지 "정의에 related_name 인수 추가" (0) | 2020.12.07 |
Linq 구별-개수 (0) | 2020.12.07 |