If I have a value class, can I modify its underlyi...
# multiplatform
n
If I have a value class, can I modify its underlying value in constructor somehow? Here’s what I mean, more or less (this won’t compile though):
Copy code
value class ValueClass(val impl: SomeOtherType) {
    init {
        this.impl = impl.somePreprocessingReturningAnotherImpl()
    }
}
b
You can do something like this
n
Thanks @Bhullnatik, looks nice, although one still has to pay attention in
ValueClass
methods to invoke the hacked factory instead of the actual constructor.
but it indeed makes the external interface much nicer!
b
Since the
constructor
is private it should call the
invoke
operator if I’m not mistaken, but anyway I’d go this route for your problem, to have a factory method somewhere and force its use
n
what bothers me is that if SomeOtherTypes comes from Java, it will be converted to ValueType for Kotlin APIs using the constructor
not the magic object method
p
i would suggest that you don’t want to do what you originally suggested in any case (calling out to some undefined code from the constructor). that advice is as old as effective java - and in fact, item 1 in that book recommends considering using static factories rather than constructors (see here for some reasoning around that). I think that a static factory method and a private constructor sounds like the way to go - whether it’s an invoke method on the companion object, or something else is up to you. so I agree with jimmy 🙂
n
In my case the code is pretty much defined, it’s
BigDecimal.stripTrailingZeros()
. Thanks for the input and pointers!