Aaron_ab
Aaron_ab

Reputation: 3758

How to convert between collection types - Set to ListSet in Scala

I have a Set in my code which i need to transfer to ListSet. It feels like a very easy thing to do, but i feel like an idiot not to be able to do it

Some code to illustrate the issue:

import scala.collection.immutable.ListSet

val someData = Set(1,2,3)

//Need to transfer to ListSet
val listSetOfData: ListSet[Int] = someData.toListSet //?

Please assist

Upvotes: 1

Views: 235

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

In Scala 2.12 (and presumably future Scala versions) you can use the to method to convert to practically any collection type:

scala> someData.to[ListSet]
res0: scala.collection.immutable.ListSet[Int] = ListSet(1, 2, 3)

In 2.11 and earlier you'll see people use a number of different ways to do this kind of thing:

scala> ListSet(someData.toSeq: _*)
res1: scala.collection.immutable.ListSet[Int] = ListSet(1, 2, 3)

scala> ListSet.empty[Int] ++ someData
res2: scala.collection.immutable.ListSet[Int] = ListSet(1, 2, 3)

Personally I think I prefer the ++ version, but it's largely a matter of taste.

Upvotes: 5

Related Questions