Can function parameters be specified to accept eit...
# getting-started
m
Can function parameters be specified to accept either of two types? My use case is functions accepting either a ResourceStringDesc or ResourceFormattedStringDesc (from Moko Resources).
r
Not currently, no. What you are looking for is called "union types", and there is a proposal for it, but no saying if, let alone when, it will every be part of the language. In the mean time, you can just have two functions:
Copy code
fun doTheThing(resource: ResourceStringDesc, ...): ...
fun doTheThing(resource: ResourceFormattedStringDesc, ...): ...
m
Thanks for that. Writing different types is a pain in this situation, I'm passing errors up a chain of calling, so there are several "double function" definitions required, which is very tedious. 😞
r
If you control the types, you could make a sealed base class and use that:
Copy code
sealed class ResourceDesc
class ResourceStringDesc : ResourceDesc()
class ResourceFormattedStringDesc : ResourceDesc()

fun doTheThing(resource: ResourceDesc)
If you don't you could do the same thing with wrappers, and just include some helpers:
Copy code
sealed class ResourceDescWrapper
class ResourceStringDescWrapper(val original: ResourceStringDesc) : ResourceDescWrapper()
class ResourceFormattedStringDescWrapper(val original: ResourceFormattedStringDesc) : ResourceDescWrapper()

fun doTheThing(resource: ResourceDescWrapper)
fun doTheThing(resource: ResourceStringDesc) = doTheThing(ResourceStringDescWrapper(resource))
fun doTheThing(resource: ResourceFormattedStringDesc) = doTheThing(ResourceFormattedStringDescWrapper(resource))
That might help clean up the chain, but depends on your use case.
βž• 2
m
Yes, fully under my control. Ok, I'll have to look up sealed classes
πŸ™ 1
πŸ‘ 2
w
m
Trying to, but it looks like a YouTrack account is different from a JetBrains account, or at least my JB account details don't let me log in to YouTrack. 😞
The "double function" solution is also really annoying when both functions are exactly the same except for the parameter type. Both ResourceStringDesc and ResourceFormattedStringDesc use the same name method to produce a string. πŸ€”πŸ˜ž
w
They sound like they are really good candidates to be expressed as a sealed type πŸ™‚
☝️ 1
m
Falls foul of the "single module" restriction I think. I'm not clear what "indirect sealed types" are, which seem to make that restriction go away.
s
Why not use an interface?
βž• 3
m
I'm not sure how that would help @sciack. I still have to have double definitions in the interface, don't I?
r
No, you just define an interface with your
produceString
function that both
ResourceStringDesc
and
ResourceFormattedStringDesc
inherit from. Then your
doTheThing
function takes the interface as a parameter. https://pl.kotl.in/0buyunEgN