问题
Code Example:
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)
}
You can use my playground for your testing! Click here.
回答1:
I believe that Kotlin doesn't have an equivalent feature. There is no default literal in Kotlin. Kotlin doesn't initialize class fields to any default, not even primitives (unlike Java, where, for example, an int is initialized to 0).
You either have to initialize your fields in the primary constructor, or at declaration, or make them nullable and leave them uninitialized (null).
Kotlin allows you to specify defaults for parameter values in the constructor, but that needs to be an instance of a concrete class, so that cannot take the generic into account.
You could use a factory method to generate a default value instead:
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")
}
来源:https://stackoverflow.com/questions/61159046/is-there-any-equivalent-of-cs-default-keyword-for-kotlin