I have a variety of base types that I add extensio...
# announcements
t
I have a variety of base types that I add extensions too (e.g. a foobar property), and I’d like to fetch foobar from a heterogenous collection of Any’s when/if they support it, otherwise do a default/fallback thing
s
it kinda sounds like you want traits?
which aren’t a thing in Kotlin
k
Or duck typing.
s
definitely not a thing in Kotlin lol
t
well… what I want is to emulate something I did in Swift (definitely not duck typed or traited)
in Swift, I can create a protocol for said foobar property, and then I can extend base types with said protocol and add implementations. then I can write code like: if let foobarable = thing as? Foobarable { foobarable.foobar } else { do_the_fallback_thing }
s
protocol extensions are definitely very trait-like, and is still not a thing you can do in Kotlin if you don’t own the class 😕
t
fair enough. is there an alternate pattern that would be workable? Is there enough reflection available in Kotlin on top of Java to determine if said static extension exists and invoke it if it does?
s
hmm I suppose I can’t rule out a reflection-based approach but I know it’s probably going to be kinda messy
would have to defer to someone with more reflect experience than I
s
There’s a KEEP out there from the Arrow folks that would enable constructs like this: https://quickbirdstudios.com/blog/keep-87-typeclasses-kotlin/ https://github.com/Kotlin/KEEP/pull/87
t
thanks guys
j
Why is this not just a normal interface? Must be missing something.
k
Generally because you don't control the classes themselves.
j
Well, in this case I think he does?
when (bob) is Foobarable -> bob.foobar() else -> whatever()
m
maybe what you’re after could be realized with the Abstract Document pattern: http://ageofjava.com/java/Type-Safe-Views-using-Abstract-Document-Pattern (Java implementation but no-brainer to port it over Kotlin)
j
Well, that is just interfaces! 😄