I've encountered a problem.
The classes I have in reality are more complex, but here's the general outline. There's a class A:
open class A(
val id: Any
)
And class B that bounds that Any
to a more specific class:
class B<T>(
val clazz: Class<T>,
nonnull: T
) : A(nonnull)
But it won't compile as T
is by default bounds to Any?
, and class A has a non-nullable Any
. And usually I'd write where T : Any
, or even where T : OneInterface, SecondInterface
. But it does not compile. I am sure I'm just writing something wrong way, but what?..
I've tried both googling and looking into the documentation, but I am not the master of Google-Fu, and documentation is silent on this matter. Both Inheritance and Generics are easy to understand, but they lack this exact intersection of language syntax. :/
CodePudding user response:
Put the constraint in a different place:
class B<T: Any>(
val clazz: Class<T>,
nonnull: T
) : A(nonnull)
Or
class B<T>(
val clazz: Class<T>,
nonnull: T
) : A(nonnull) where T: Any
I'd prefer the first one and only use where
when you can't use it, e.g. for multiple constraints.
CodePudding user response:
Restrict T to not accept a nullable Any:
class B<T: Any>(
...