Current intersection-type options in Kotlin

Hate to be the um actually guy, but this is technically possible, it’ll just look odd from the Java calling side. (The following explanation is paraphrased from this Slack thread). The stdlib actually defines a function that looks like this:

@kotlin.internal.InlineOnly
public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R

The trick here is in the InlineOnly annotation since the checker has an exception for it.
That exception is there in the checker because the only problem with this feature is that it breaks Java compatibility as explained in this StackOverflow post, and so if a function is InlineOnly it can be called only in Kotlin and it never exists in the bytecode, thereby solving that problem, and so, if you want to enable this you can either use this trick to shadow the internal annotation, or you can suppress the error using @Suppress("BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER") (Playground example). If you’re going to suppress that error, then I’d suggest that, just in case you really care about Java compat, that you make that function inline and make one of the type parameters reified because reified inline functions don’t actually exist in the bytecode.

And yeah, using one of the aforementioned tricks you can then use that intersection function. I wonder what the possibilities could be with that function available on the type system! I don’t think it’d be anything major but it could be useful. I guess at the very least you’d be able to return an intersection type, and so in your example you can define an asIntersection3() possibly.

1 Like