【发布时间】:2021-03-11 19:03:16
【问题描述】:
我有一个自定义日期类,它的主要构造函数如下:
class CustomDate(val day : Int, val month : Int, val year : Int)
{
init {
...some processing...
}
}
我需要辅助构造函数,它以字符串“01.01.2021”的形式获取日期,并在调用主构造函数之前将它们拆分为日、月和年:
constructor(date : String) { ...some processing over date string that gives day, month and year... }
: this(day, month, year)
{
...do stuff...
}
目前我只能想到做:
constructor(date : String) : this(0, 0, 0) {
... do processing on date string and assign new values to fields instead of 0s ...
}
但这看起来有点难看,如果有一种在调用主构造函数之前进行处理的方法,就像我在构造函数的第一个示例中提到的那样
【问题讨论】:
标签: class kotlin constructor