Does Kotlin have any secret feature for automatica...
# announcements
d
Does Kotlin have any secret feature for automatically overriding the return type of builder methods in subclasses?
s
Hmmm, I think I might know what you want but would you mind clarifying
spoiler: it’s not a “secret” feature, just kind of a hack tbh
d
Copy code
TrackableMailMessage mailMessage = (TrackableMailMessage) new TrackableEmailBuilder(this)
                .to(emailAddresses)
                .locale(locale)
                .subject(subject)
                .body(content)
                .buildMailMessage();
TrackableEmailBuilder extends EmailBuilder but buildMailMessage() returns MailMessage instead of TrackableMailMessage because each of the setter methods are defined in EmailBuilder
(obviously this is the usage in java)
s
Hmm, is
EmailBuilder
maybe an abstract class?
d
it’s a sealed class in this case
it could be abstract but ¯\_(ツ)_/¯
s
No, that’s fine, sealed types are basically abstract classes
or, well, gimme a sec to test something real quick before I commit to that statement lmao
d
alright
s
Okay, so, if you want to have overridable return types in child builder classes, you can abuse generics to do so
Well, in your case specifically it wouldn’t really be abuse, unless you wanted bootleg self types
actually yeah in your case I’d just include a
<T>
in your sealed builder definition and then define
abstract fun buildMailMessage(): T
d
oh right
👍 1
iirc, it’s the same thing in java
s
yep