Anyone know if its possible to have a generic func...
# getting-started
s
Anyone know if its possible to have a generic function accept both a non-null and nullable enum? I current have an func. built like this
Copy code
fun <P : Enum<P>> BaseConstraints<out Any, P>.validEnum(
    init: Unit.() -> Unit
) {
    this.rules.add(ValidEnum())
}
and it is only valid when I do
validEnum<Status> {  }
(where Status is my enum) but not when I do
validEnum<Status?> {  }
. I can make it accept the latter by doing
Copy code
fun <P : Enum<P>> BaseConstraints<out Any, P?>.validEnum(
    init: Unit.() -> Unit
) {
    this.rules.add(ValidEnum())
}
but then I am unable to do
validEnum<Status> {  }
Figured out I can do this instead
Copy code
@JvmName("validEnumAnyP")
fun <P: Enum<P>> BaseConstraints<out Any, P>.validEnum(
    init: Unit.() -> Unit
) = this.rules.add(ValidEnum())

@JvmName("validEnumAnyP?")
fun <P: Enum<P>> BaseConstraints<out Any, P?>.validEnum(
    init: Unit.() -> Unit
) = this.rules.add(ValidEnum())
y
You could have
fun <P: Enum<P & Any>?>
I think, since then both
Status
and
Status?
extend
Enum<Status>?
s
Thanks, that seems to work! If I am reading this correctly, doing
P & Any
is as if doing
P: Any
y
Sort of, what it is really doing is that, AFAIK,
Enum<T>
requires
T : Enum<T>
, and NOT
T : Enum<T>?
, But we would like to make our
P
here nullable within the type parameters, and so we simply make it possibly nullable, but we ensure to only pass the non-nullable kind to
Enum
so that it compiles correctly.
s
I see, thanks!