swift - Kotlin 是否支持像 swift 这样的可选构造函数?

标签 swift kotlin constructor

我想在 Kotlin 中使用一个可选的构造函数,它要么创建一个对象,要么返回 null。

这是一个 Swift 示例,展示了我希望它如何工作:

class Beer {
    init?(yourAge : Int){
        if yourAge < 21 {
            return nil
        }
    }
}
Beer(yourAge: 17) //is nil
Beer(yourAge: 23) //a Beer object

我当然可以将检查放在另一个函数中(下面是与前面示例等效的 Kotlin),但它不是那么好

class Beer(){
    fun initialize(yourAge : Int): Beer? {
        if (yourAge < 21){
            return null
        }else {
            return Beer()
        }
    }
}

最佳答案

正如 Yole 所说,Kotlin 不支持可选的构造函数,但您可以使用在伴生对象中定义的调用运算符来实现您想要的:

class Beer {
    companion object {
        operator fun invoke(yourAge: Int) = if (yourAge < 21) {
            null
        } else {
            Beer()
        }
    }
}

Beer(17) // null
Beer(23) // instance of Beer

关于swift - Kotlin 是否支持像 swift 这样的可选构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54147909/

相关文章:

immutability - Kotlin 实例化不可变列表

android - 仅当缓存时发生错误:通过改型实现缓存

java - 将值应用于对象时出错

c++ - 为什么我在 main 中声明的变量被初始化,就好像它是我的类的变量一样?

ios - 从字符串swift 3中获取特定范围的字符

ios - 如何在 iOS 中获取唯一的设备 ID

android - Kotlin 单元测试未找到模块依赖接口(interface)

c++ - WxWidgets:麻烦调用 wx Frame Constructor

ios - 在没有 API 的情况下以 swift 显示网页内容

ios - 如何在 Swift 中暂时停止使用某个方法?