Michael Marshall
10/31/2022, 2:01 AMfun <A, B> myFunction(a: A, b: B) where A !: B {
...
}
Joffrey
10/31/2022, 2:54 PMMichael Marshall
11/02/2022, 12:51 AMProxy.newProxyInstance()
method which requires the interface you’re proxying to be passed in. I also need to pass in a variable which implements that interface. Unfortunately at the call site, it’s easy to accidentally pass in the concrete class for both generic params as the compiler will infer it (if you don’t explicitly write them) and there will be no compile time errors.
A simplified version looks like this
inline fun <reified Concrete, reified Interface> makeProxy(concrete: Concrete) where Concrete : Interface {
...
return newProxyInstance(
apiClass = Interface::class.java.classLoader,
arrayOf(Interface::class.java),
MyCustomProxyClass(concrete as Interface),
) as Interface
}
And the call site looks like
fun doStuff(): MyInterface {
makeProxy(MyConcreteClass()) // <--- In some places the compiler reads this as makeProxy<MyConcreteClass, MyConcreteClass>(MyConcreteClass())
}
Joffrey
11/02/2022, 12:53 AMmakeProxy
?Michael Marshall
11/02/2022, 12:56 AMJoffrey
11/02/2022, 12:58 AMmakeProxy
function take 2 parameters:
fun <I, I : C> makeProxy(concrete: C, target: KClass<I>): I {
...
return newProxyInstance(
apiClass = target.java.classLoader,
arrayOf(target.java),
MyCustomProxyClass(concrete),
) as I
}
So the call site will be forced to provide both arguments, and cannot rely solely on type inference:
fun doStuff(): MyInterface {
makeProxy(MyConcreteClass(), MyInterface::class)
}
Michael Marshall
11/02/2022, 1:00 AMinline
version calls it. The problem is that’s not as pretty or nice to use 😂 Ideally the callsite just looks like
MyConcreteClass().makeProxy()
(the class is actually the receiver param in my code)
This requires the encapsulating function to specify MyInterface
as the return type ofcMichael Marshall
11/02/2022, 1:04 AMJoffrey
11/02/2022, 1:04 AMMichael Marshall
11/02/2022, 1:07 AMX
or any of its subclasses, or
2. A generic type param is an interface
and not a class
Applying either of those restrictions could help