https://kotlinlang.org logo
a

allan.conda

07/20/2021, 10:15 PM
I’m looking for ideas on designing an interface in Kotlin. 🙏 I’d like to keep the data type as simple as a String. I want different classes to take that String, and I want to write extension convenience functions for that particular type of String. I think I have to Box the string, but wondering if there’s a nice Kotlin to seamlessly unbox the Strings. Sample code in thread
Copy code
class EventTypeA(eventName: String)
class EventTypeB(eventName: String)

// this type of string is in a particular format, and can be interpreted in another format
fun String.convertToAnotherFormat() { ... }
Copy code
data class EventName(value: String)
I think this will work, just wondering if there’s a better way to represent a “particular type of String” kind of like just extending the String. I just want a particular set of convenience function only work for these Strings. Something like
typealias
but that one still allows these functions to be used in any String because it’s just an alias
h

Hanno

07/20/2021, 10:24 PM
No, there is no such thing as implicit conversion in kotlin. Or tagged types. You always need conversion methods that are explicitly called, or your instance is just as good as any other string. Where do you need to convert that thing ever back to a string? Or which methods of string are you actually interested in not to lose by wrapping?
👍 1
a

allan.conda

07/20/2021, 11:06 PM
I see. Basically all its consumers like API calls just expect a string, and all the inputs come from providers as a String as well. So there will always be that boxing and unboxing happening.
p

Paul Griffith

07/20/2021, 11:46 PM
Value classes are kind of what you want - they're a kind of 'specific subset of some type', but you'll still need to "unbox" to pass them to external libraries (or provide your own extension methods, but then you'll still have conflicting visibility) https://kotlinlang.org/docs/inline-classes.html
🙏 1
a

allan.conda

07/21/2021, 10:14 AM
Looks promising! Let me try it
h

Hanno

07/21/2021, 6:58 PM
Why do callers prefer a string? When they get a string they also have to suffer from not getting any type guarantees when they use it further down their code paths. Sometimes the user has to be shown the advantages he gets :). Only when thats also supporting the usages of course. To string usage could most often be implemented AS expected, so i would look at the callers use cases.
2 Views