然而,在Kotlin中,默认情况下具有getter和setter。但我不知道如何使用它们。
我想让它与Java类似:
private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.
那么getter如何工作?
private val isEmpty: String
get() = this.toString() //making this thing public rises an error: Getter visibility must be the same as property visibility.
Kotlin会自动生成Getter和Setter。如果你写:
val isEmpty: Boolean
它等同于以下Java代码:
private final Boolean isEmpty;
public Boolean isEmpty() {
return isEmpty;
}
在您的情况下,private 访问修饰符是多余的 - isEmpty默认为private,并且只能通过getter访问。当您尝试获取对象的isEmpty属性时,实际上会调用get方法。要了解有关Kotlin中getter / setter的更多理解:下面的两个代码示例是相等的:
在您的情况下,private 访问修饰符是多余的 - isEmpty默认为private,并且只能通过getter访问。当您尝试获取对象的isEmpty属性时,实际上会调用get方法。要了解有关Kotlin中getter / setter的更多理解:下面的两个代码示例是相等的:
var someProperty: String = "defaultValue"
andvar someProperty: String = "defaultValue"
get() = field
set(value) { field = value }
另外,我想指出,在 getter 方法中的 this
不是您的属性 - 它是类实例。如果您想要在 getter 或 setter 中访问字段的值,可以使用保留关键字 field
:
val isEmpty: Boolean
get() = field
如果您只想要一个公共访问的get方法-可以编写此代码:
var isEmpty: Boolean
private set
由于 set 访问器旁边的 private 修饰符,您只能在对象内部的方法中设置此值。
有关属性访问器可见性修饰符的规则如下:
Getter visibility of var
and val
property should be exactly the same to the visibility of the property, thus you can only explicitly duplicate the property modifier, but it is redundant:
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.
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) { }
x
设置为 "Some String"
并返回字符串的长度,即 11
。 - CarelKotlin中属性firstName
的默认setter
和getter
示例:
1) 示例默认 setter
和 getter
for property firstName
in Kotlin
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)
如果您的setter
或getter
与以上内容完全相同,则可以删除它,因为它是不必要的
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,所以我对field
和property
感到困惑,因为在Java中没有property
。
经过一些搜索,我发现Kotlin中的field
和property
看起来像C# (What is the difference between a field and a property?)
这里有一些相关的帖子,谈论Java和Kotlin中的field
和property
。
does java have something similar to C# properties?
https://blog.kotlin-academy.com/kotlin-programmer-dictionary-field-vs-property-30ab7ef70531
如果我错了,请纠正我。希望这有所帮助。
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}")
}
如果您有一个变量,则可以执行以下操作:
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
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.
// 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"