是否有C#的“默认"等价物? Kotlin的关键字? [英] Is there any equivalent of C#'s "default" keyword for Kotlin?

查看:111
本文介绍了是否有C#的“默认"等价物? Kotlin的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码示例:

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.

推荐答案

我相信Kotlin没有等效功能.没有默认文字在科特林. Kotlin不会将类字段初始化为任何默认值,甚至也不会初始化为基元(与Java不同,例如,Java将int初始化为0).

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允许您在构造函数中指定参数值的默认值,但是它必须是具体类的实例,因此不能考虑泛型.

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")
}

这篇关于是否有C#的“默认"等价物? Kotlin的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆