How do I use delegation on a member that I don't w...
# announcements
n
How do I use delegation on a member that I don't want to declare in the primary constructor?
n
I don't think you can, unfortunately. Also, there isn't the 'generate delegate methods' like there is in java 😞
n
Do you know if there's a reason?
n
I'm guessing because delegated methods aren't polymorphic
n
Not sure I follow that
if you have a member that's e.g. a
Map<K, V>
delegation shouldn't care about the details of how that member is initialized
it seems totally orthogonal to delegation
n
I mean if the delegated property came from the constructor, that property can't mutate.
n
wait, what? What's stopping it from mutating?
n
I don't think you can delegate to an open val
fact check needed though
n
you can but you get a warning. but this is the strangest warning I've ever seen
delegation to a var property does not take changes into account...
that's a pretty big wtf
n
that's what I meant about it not being polymorphic.
at this point I'd settle for what they do in Java, which is just 'generate delegate methods'
n
Well, it still is polymorphic; the actual delegate calls will get dispatched based on the actual object you have
the member type can itself be an interface
e.g. if you have class foo(val data: Map<K, V>) : Map<K, V> by data
n
yeah, I'm probably using the wrong term. I just mean that the delegated member can't change
n
right. pretty bizarre.
delegation doesn't work remotely how I imagined, given this
n
functionally you can get the same effect of what you're trying to do by just implementing all methods and writing the delegation manually. It's just verbose and tedious
n
I found a workaround, for my specific issue
arg
Copy code
class ImmutableMap<K, V> private constructor(x: Int, var data: Map<K, V>) : Map<K, V> by data {
    
    constructor(x: Map<K, V>) : this(0, x.asSequence().associate_regular { it.toPair() })
basically, since the primary constructor is private anyway
we just add an unused parameter 🙂
to change the signature
n
ha, yep, I've done exactly that before
sometimes the code to create the delegate object in the secondary constructor gets gnarly though..
n
yeah, I bet
n
oi, I'm still banging my head on the wall trying to figure out why IDEA doesn't like my gradle.kts files
oh finally! deleted the JBR runtime that came with IDEA and that fixed it
n
🙂