kotlin - 完成一些计算后从辅助构造函数调用主构造函数
问题描述
基本问题。我有一个主构造函数和一个辅助构造函数,在辅助构造函数中我计算/获取主构造函数
这是一个问题,因为据我所知,您需要立即在第二个内部调用主构造函数。
像这样
constructor() : this(/*parameters for primary constructor*/)
但是,我不能调用主构造函数,因为我还不知道参数。
constructor() : this(/*???*/) {
//find parms of primary constructor
//i want to call primary constructor here
}
是否可以稍后在辅助构造函数中调用主构造函数?
有没有更好的方法来构建它以避免这个问题?
这是一个过于简单的例子
class Test(var name: String,var age: String,var dateOfBirth: String){
constructor(id: String) : this(/*???*/) {
//get name, age, dob, from id
I want to call the primary constructor here since
}
}
我最好的解决方案是简单地将空/空值发送到主构造函数,然后在构造函数的主体中更改它们
constructor(id: String) : this(null,0,null) {
name =
age =
dateOfBirth =
}
这行得通,但我想知道是否有更好的方法
很可能有一种更好的方法来构建整个事情,这将完全避免这个问题,所以如果是这样,请告诉我!
解决方案
您应该避免在构造函数内部使用任何计算。一般来说,这是一种不好的做法。我对您的建议是使用构建器函数。就像是:
class Test(
var name: String,
var age: String,
var dateOfBirth: String) {
companion object {
fun fromId(id: Long): Test {
//calculations
return Test("", "", "")
}
}
}
推荐阅读
- laravel - Vuejs / Laravel 路线在生产中不起作用
- ios - 如何在单个 Xcode 项目中添加多个框架?
- database - DynamoDB 中的默认索引
- django - 如何在没有权限被拒绝错误的情况下在 Windows 路径上安装 virtualenv?
- performance - Jenkins 管道性能,构建图提取
- django - celery 任务将 python 列表转换为字符串。如何避免这种情况?
- c - 如何解析数组的一个索引中的字符串?
- reverse-engineering - Windbg .sys 文件上的本地内核调试
- php - 为什么 php-fpm status max active processes 可以大于 pm.max_children?
- javascript - React Redux 表单(多种表单) - 路由和状态处理问题