Adding CharRange to Set

On the following documentation page for “Set” collection:

there are definitions for functions plus and plusElement which have identical descriptions. But the results of those functions are not identical.

plusElement definition:

Returns a set containing all elements of the original set and then the given element if it isn’t already in this set.
fun Set.plusElement(element: T): Set

plus definition:

Returns a set containing all elements of the original set and then the given element if it isn’t already in this set.
operator fun Set.plus(element: T): Set

plusElement result (in Kotlin REPL)

setOf(‘a’…‘z’, ‘A’…‘Z’).plusElement(‘0’…‘9’)
res3: kotlin.collections.Set<kotlin.ranges.CharRange> = [a…z, A…Z, 0…9]

plus result:

setOf(‘a’…‘z’, ‘A’…‘Z’).plus(‘0’…‘9’)
res4: kotlin.collections.Set<kotlin.Any> = [a…z, A…Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Is this difference in behavior intended?

The problem here is that you’re using a different overload of plus, that takes CharRange as a collection of elements rather than as a single element. This is unexpected, but this is how overload resolution currently works in Kotlin. The issue https://youtrack.jetbrains.com/issue/KT-9992 was created to track this problem.

plusElement was introduced as a workaround for this exact problem, to specify that you want to treat argument always as a single element and not as a collection.