Hey, I have a question regarding bounds on generic...
# announcements
a
Hey, I have a question regarding bounds on generic types. In the Kotlin stdlib there this function:
Copy code
@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
    if (isEmpty()) defaultValue() else this
You can call it and it works great. However, if I simply copy this function into my code (with intention to later have a slightly modified version), it simply does not compile:
Copy code
public inline fun <C, R> C.ifEmpty2(defaultValue: () -> R): R where C : CharSequence, C : R =
    if (isEmpty()) defaultValue() else this
Produces error highlighting `CharSequence`:
Copy code
Type parameter cannot have any other bounds if it's bounded by another type parameter
You can find the example here: https://pl.kotl.in/oGzbGuXah Why is this the case? Why can’t I use the same features used in stdlib?
a
It's because kotlin compiler skips the check when
@kotlin.internal.InlineOnly
annotation is present. Source here.
a
Thank you for the explanation! This does not seem fair for the language users though…
y
well there's multiple ways that you can surpass that error for now (because yes eventually this'll be stopped but according to the folks in the Kotlin team useful annotations like inline only will be available to the public somehow):
Copy code
@Suppress("BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER")
Or for the "future-proof" solution:
Copy code
@file:Suppress("INVISIBLE_MEMBER, INVISIBLE_REFERENCE")

@kotlin.internal.InlineOnly fun...
Or if you don't want any compiler error suppression, then create a file with the package
kotlin.internal
and copy over the code for
@InlineOnly
and then you'll be able to use it right away.