代码示例:
import java.util.UUID
interface InterfaceOne<AType> {
var abcOne:AType
}
interface InterfaceTwo<AType> {
var abcTwo:AType
}
class Example<AType>: InterfaceOne<AType>, InterfaceTwo<AType> {
override var abcOne: AType // Looking for default value to not from constructor
set(value) {
field = value
//...
}
override var abcTwo: AType // Looking for default value to not from constructor
set(value) {
field = value
//...
}
fun test(uuid: AType) {
abcTwo = uuid
abcOne = default // I'm looking for C#'s default keyword equivalent in here
}
}
fun main() {
val uuid = UUID.randomUUID()
val uuid2 = UUID.randomUUID()
val interfaceOne = Example<UUID>()
interfaceOne.test(uuid)
}
您可以使用我的 Playground 进行测试! Click here .
最佳答案
我相信 Kotlin 没有等效的功能。没有 default literal在 Kotlin 。 Kotlin 不会将类字段初始化为任何默认值,甚至不会初始化基元(与 Java 不同,在 Java 中,例如,int
被初始化为 0)。
您要么必须在主构造函数中或在声明时初始化您的字段,要么使它们可为空并保持未初始化(null)。
Kotlin 允许您在构造函数中为参数值指定默认值,但这需要是具体类的实例,因此不能考虑泛型。
您可以使用工厂方法来生成默认值:
class Example<AType>(val factory: () -> AType): InterfaceOne<AType>, InterfaceTwo<AType> {
override var abcOne: AType = factory()
override var abcTwo: AType = factory()
fun test(uuid: AType) {
abcTwo = uuid
abcOne = factory()
println("abcOne=$abcOne")
println("abcTwo=$abcTwo")
}
}
fun main() {
val uuid = UUID.randomUUID()
val uuidExample = Example<UUID>({UUID.randomUUID()})
uuidExample.test(uuid)
val stringExample = Example<String>({"default"})
stringExample.test("two")
}
关于generics - Kotlin 是否有等效于 C#'s "default"的关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159046/