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

Travis Griggs

10/20/2023, 4:41 PM
Is there an easy way to create a Set<Int> from an OpenEndRange<Int>? I wanted to just do
setOf(*(0..<15))
, but the spread operator doesn't like using a Range? (in my case, the range is programatically created, rather than a literal as shown there)
k

Klitos Kyriacou

10/20/2023, 4:44 PM
If it's actually an
IntRange
you can use
range.toSet()
. It doesn't work for an
OpenEndRange<Int>
t

Travis Griggs

10/20/2023, 4:51 PM
Why is that?
s

Shawn

10/20/2023, 4:51 PM
wait, no
Copy code
(0..<15).toSet()
works just fine
kodee happy 1
k

Klitos Kyriacou

10/20/2023, 4:52 PM
Because there's no guarantee that an
OpenEndRange<T>
contains a finite number of Ts. It does for
Int
, but that's just a special case. What would you say
("Alpha"..<"Zulu").toSet()
should contain?
(0..<15).toSet()
works fine because
(0..<15)
is an
IntRange
, which implements the
OpenEndRange<Int>
interface, but importantly it also implements
Iterable
.
t

Travis Griggs

10/20/2023, 5:00 PM
thanks
s

Shawn

10/20/2023, 5:05 PM
okay, well, when defining a range containing a finite number of elements with a defined ordering, such as
Int
, like Travis asked,
.toSet()
works.