I'm looking at a way to be able to produce an anon...
# announcements
s
I'm looking at a way to be able to produce an anonymous object that implements multiple interfaces, but seemingly missing something with the below resulting in a
Type mismatch. Required: P, Found: <P>
error for the returned value.
Copy code
interface A
interface B
interface C

fun <P> resolve(): P where P : A, P : B, P : C {
    return object : A, B, C {}
}
Is there some variation of this that is possible?
s
Copy code
interface A
interface B
interface C
interface P : A, B, C

fun resolve(): P {
    return object : P {}
}
s
It would be great if it didn't require an extra interface, as there will end up being many combinations.
Copy code
inline fun <reified P> resolve(): P where P : A, P : B, P : C {
    return object : A, B, C {} as P
}
This seems to not complain
Just not sure whether it is considered correct/idiomatic
s
as P
is what makes it work, I think.
s
yeah, along with the
<reified P>
s
That is because you can't extend from or implement a generic type parameter, unless it is reified.
In your original example
P : A, B, F
is not the same as
Q : A, B, C
, where
Q
is the
object
in your code.
s
Not the same, though I would have assumed it was safe to cast, given the constraints
We can stick with reified version, it just means we need to shuffle some things around to deal with the fact that it is now inlined.
r
The user can specify
P
, so you can't guarantee you're returned object will match what they expect.
s
Yup, and that actual sub-type of
P
may expect a method that your returned
object
does not provide.
s
In our case, the interfaces are empty for the purpose of tagging and polymorphic at the call-site too, so I don't believe that should cause us any problems.
We ended up getting stuck with not being able to utilise Java interop with the
inline
/`reified` properties, so we're back to utilising a (likely simpler) solution with data classes instead. Thanks for your help though.
k
Your reified p solution would have always thrown a cast exception
s
At runtime or compile time?
k
At runtime
s
I’m not near a computer to try it out now, but even though they were just being used as phantom types? As in, no methods would ever attempt to be called against any of the interfaces.
I would’ve hoped that would be a compile-time warning if it’s going to potentially result in a runtime exception.
s
Didn't the compiler give a warning that
as P
is an unsafe type cast?
s
Not that we noticed. Without the refined type it did though.