Is there any equivalent of C#'s “default” keyword for Kotlin?

我的梦境 提交于 2020-05-15 10:04:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!