Reputation: 16723
One of my methods return a List[(String,Option[Int])]
. I convert it into a Set
calling toSet[(String,Option[Int])]
method of List
question 1 - would this give me a Set[(String,Option[Int])]
?
then I have a case class which can map the data of the Tuple(String,Option[Int])
case class TagCount
case class TagCount (tag:String,count:Int)
Is it possible that using the toSet
method of the List
, I actually get a Set[TagCount]
instead of `Set[(String,Option[Int])]
I notice that toSet
can accept type argument B >: (String,Option[Int])
but I can't figure out how to make TagCount >: (String,Option[Int])
def toSet[B >: A]: Set[B]
Upvotes: 2
Views: 89
Reputation: 48420
Assuming tuple matches the case class field types exactly
case class TagCount(tag: String, count: Option[Int])
val s: Set[(String, Option[Int])] = Set("a" -> Some(42), "b" -> Some(11), "c" -> None)
we could get Set[TagCount]
using tupled
method like so
s.map(TagCount.tupled)
which outputs
res1: scala.collection.immutable.Set[TagCount] = Set(TagCount(a,Some(42)), TagCount(b,Some(11)), TagCount(c,None))
Upvotes: 2
Reputation: 9168
You can try:
def foo(in: List[(String, Option[Int])]): Set[TagCount] =
in.toSet.collect {
case (key, Some(c)) => TagCount(key, c)
}
Upvotes: 1