Kotlin 的引导者和引导者

例如,在 Java 中,我可以自己编写 getter (由 IDE 生成) ,或者在 lombok 中使用像@Getter 这样的注释——这非常简单。

然而科特林有 getters and setters by default。 但我不知道怎么用。

我想让它,让我们说-类似于 Java:

private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.

那么获得者是如何工作的呢?

147500 次浏览

在 Kotlin,读取器和设置器都是自动生成的。如果你写道:

val isEmpty: Boolean

它等于以下 Java 代码:

private final Boolean isEmpty;


public Boolean isEmpty() {
return isEmpty;
}

在您的情况下,私有访问修饰符是多余的-isEmpty 在默认情况下是私有的,只能由 getter 访问。当您尝试获取对象的 isEmpty 属性时,您将在 real 中调用 get 方法。为了更好地理解 Kotlin 的 getters/setter,下面的两个代码示例是相等的:

var someProperty: String = "defaultValue"

and

var someProperty: String = "defaultValue"
get() = field
set(value) { field = value }

Also I want to point out that this in a getter is not your property - it's the class instance. If you want to get access to the field's value in a getter or setter you can use the reserved word field for it:

val isEmpty: Boolean
get() = field

如果你只想在公共访问中有一个 get 方法,你可以写下面的代码:

var isEmpty: Boolean
private set

由于 set 访问器附近的私有修饰符,因此只能在对象内部的方法中设置此值。

关于属性访问器 可见度修饰符可见度修饰符的规则如下:

  • varval属性的 Getter 可见性应该与该属性的 一样完全相同,因此您只能显式地复制属性修饰符,但它是多余的:

    protected val x: Int
    protected get() = 0 // No need in `protected` here.
    
  • Setter visibility of var property should be the same or less permissive than the property visibility:

    protected var x: Int
    get() = 0
    private set(x: Int) { } // Only `private` and `protected` are allowed.
    

In Kotlin, properties are always accessed through getter and setter, thus there's no need in making a property private with public accessors like in Java -- its backing field (if present) is already private. So, visibility modifiers on property accessors are only used to make setter visibility less permissive:

  • For a property with backing field and default accessors:

    var x = 0 // `public` by default
    private set
    
  • For a property without backing field:

    var x: Int // `public` by default
    get() = 0
    protected set(value: Int) { }
    

Kotlin 中的 Getter 在默认情况下是公共的,但是您可以将 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}")
}

更多信息可以参见本教程:

Android 开发者的另一个 Kotlin 教程

物业

在 Kotlin 世界中,类不能有字段,只能有 properties. var keyword tells us the property is mutable, in contrast to val. Let’s 举个例子:

class Contact(var number: String) {


var firstName: String? = null
var lastName: String? = null
private val hasPrefix : Boolean
get() = number.startsWith("+")


}

虽然没有很多代码,但是在 我们将一步一步来。首先,我们创建了一个 公共期末班联系

This is the primary rule we have to face: if not specified otherwise, 默认情况下,类是公共的和最终的(顺便说一下,对于 如果要从类继承,请将其标记为 open keyword.

1) Kotlin propertyfirstName的默认 settergetter示例

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)

如果你的 settergetter一模一样以上,你可以移除它,因为它是 不必要的

2)自定义 setter 和 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")
}
}
}

吸毒

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

更多
我从 Java 开始学习 Kotlin,所以我对 fieldproperty感到困惑,因为在 Java 中没有 property
经过一番搜索,我发现 Kotlin 的 fieldproperty看起来像 C # (字段和属性之间的区别是什么?)

下面是一些相关的帖子,讨论了在爪哇和 Kotlin 的 fieldproperty
Java 有类似于 C # 属性的东西吗?
Https://blog.kotlin-academy.com/kotlin-programmer-dictionary-field-vs-property-30ab7ef70531

如果我说错了请纠正我,希望对你有帮助

下面是 Kotlin getter 和 setter 的一个实用的、真实的例子(参见更多细节 给你) :

// Custom Getter
val friendlyDescription get(): String {
val isNeighborhood = district != null
var description = if (isNeighborhood) "Neighborhood" else "City"
description += " in"
if (isNeighborhood) {
description += " $city,"
}
province?.let {
if (it.isNotEmpty()) {
description += " $it,"
}
}
description += " $country"
return description
}


print(myLocation.friendlyDescription) // "Neighborhood in Denver, Colorado, United States"




// Custom Setter
enum class SearchResultType {
HISTORY, SAVED, BASIC
}


private lateinit var resultTypeString: String


var resultType: SearchResultType
get() {
return enumValueOf(resultTypeString)
}
set(value) {
resultTypeString = value.toString()
}


result.resultType = SearchResultType.HISTORY
print(result.resultTypeString) // "HISTORY"


If you have a Var then you can:

var property: String = "defVal"
get() = field
set(value) { field = value }

但是在 Val 的情况下,一旦分配了它,就不能设置它,因此不会有 setter 块:

val property: String = "defVal"
get() = field

或者,如果你不想要 setter,那么:

val property: String = "defVal"
private set

有点不同意@Cortwave 的最佳答案。成员字段。您必须在类中编写私有修饰符 做出来encapsulated

我在这里寻找的答案是,是否 kotlin 自动生成私有成员字段的 getter 和 setter 或者你必须自己做?Android Studio 中的简单实现表明您需要自己编写它。