https://kotlinlang.org logo
Title
d

dumptruckman

02/07/2019, 6:13 PM
Does Kotlin have any secret feature for automatically overriding the return type of builder methods in subclasses?
s

Shawn

02/07/2019, 6:14 PM
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

dumptruckman

02/07/2019, 6:15 PM
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

Shawn

02/07/2019, 6:18 PM
Hmm, is
EmailBuilder
maybe an abstract class?
d

dumptruckman

02/07/2019, 6:19 PM
it’s a sealed class in this case
it could be abstract but ¯\_(ツ)_/¯
s

Shawn

02/07/2019, 6:19 PM
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

dumptruckman

02/07/2019, 6:20 PM
alright
s

Shawn

02/07/2019, 6:23 PM
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

dumptruckman

02/07/2019, 7:06 PM
oh right
👍 1
iirc, it’s the same thing in java
s

Shawn

02/07/2019, 7:07 PM
yep