Juan B
10/09/2020, 1:54 AMval employeeRunData = EmployeeRunData(annualSalary = BigDecimal(120000))
Instead, I would like to do something like: <note there is not call to _BigDecimal(120000)_>
val employeeRunData = EmployeeRunData(annualSalary = 120000))
I would highlight that the annoyance is while writing unit test. Thank you all!Milan Hruban
10/09/2020, 6:20 AMfun EmployeeRunData(annualSalary: Int) = EmployeeRunData(annualSalary = BigDecimal(annualSalary))
Michael de Kaste
10/09/2020, 8:31 AMfun main(){
val constructWithBigDecimal = EmployeeRunData(BigDecimal.TEN)
val constructWithNumber = EmployeeRunData(2341L)
}
data class EmployeeRunData(val annualSalary: BigDecimal) {
constructor(annualSalary: Number) : this(BigDecimal(annualSalary.toString()))
}
This way, whenever you call the constructor of EmployeeRunData, it will set its annualSalary directly if you call it with a BigDecimal, otherwise it will call it with the constructor.
If your problem is in writing unittests only, I suggest just making local functionsMartin
10/09/2020, 9:40 AMfoo()
expects a BigDecimal, you could call it like foo(<http://123.bd|123.bd>)
elizarov
10/09/2020, 4:26 PMval <http://Int.bd|Int.bd> get() = toBigDecimal()
Juan B
10/13/2020, 5:52 AMMartin
10/13/2020, 8:14 AMtoBigDecimal()
as an extension function on the Int
type, so you don't need to implement that. @elizarov's solution is adding a bd
property to the Int
type, and the getter for that property delegates to toBigDecimal()
. That way, EmployeeRunData
only needs the primary constructor, which takes a BigDecimal
, and you can call it like: val constructWithBigDecimal = EmployeeRunData(<http://10.bd|10.bd>)
. Does that make more sense?Juan B
10/13/2020, 3:51 PM