https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Siddhartha Juluru

08/17/2022, 5:16 PM
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

Youssef Shoaib [MOD]

08/18/2022, 2:35 AM
You could have
fun <P: Enum<P & Any>?>
I think, since then both
Status
and
Status?
extend
Enum<Status>?
s

Siddhartha Juluru

08/18/2022, 1:12 PM
Thanks, that seems to work! If I am reading this correctly, doing
P & Any
is as if doing
P: Any
y

Youssef Shoaib [MOD]

08/18/2022, 1:21 PM
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

Siddhartha Juluru

08/18/2022, 1:27 PM
I see, thanks!
2 Views