如何从Scala中的一组字符串生成一组字符

如何从Scala中的一组字符串生成一组字符,scala,set,map-function,Scala,Set,Map Function,我想用一组字符串中的第一个字符创建一个集合。似乎我应该能够很容易地映射,但我无法找出正确的语法,也无法在SO或其他web上找到它。这就是我所处的位置: val mySetOfStrings = scala.collection.immutable.Set[String]() def charSet: Set[Char] = mySetOfStrings.map[Char]((s: String) => s.head) //IDE tells me "Expression of type

我想用一组字符串中的第一个字符创建一个集合。似乎我应该能够很容易地映射,但我无法找出正确的语法,也无法在SO或其他web上找到它。这就是我所处的位置:

val mySetOfStrings = scala.collection.immutable.Set[String]()
def charSet: Set[Char] = mySetOfStrings.map[Char]((s: String) => s.head)

//IDE tells me "Expression of type Char doesn't conform to expected type B"
谢谢

scala> Set("foo", "bar", "baz").map( s => s.head )
res0: scala.collection.immutable.Set[Char] = Set(f, b)
您通常不会自己向map方法提供类型参数


您通常不会自己为map方法提供类型参数。

如果要忽略输入中的空字符串,则可以使用:

mySetOfStrings.flatMap(_.headOption)

如果要忽略输入中的空字符串,则可以使用:

mySetOfStrings.flatMap(_.headOption)

IDE错误不正确,但是手动向
map
提供类型参数会给您带来问题,因为
map
的签名实际上是:

final def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
因此,实际的编译器错误是:

<console>:12: error: wrong number of type parameters for method map: [B, That](f: String => B)(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Set[String],B,That])That
       strings.map[Char](_.head)
                  ^
手动提供类型参数必须如下所示:

scala> strings.map[Char, Set[Char]](_.head)
res6: Set[Char] = Set(a, d, i)

IDE错误不正确,但是手动向
map
提供类型参数会给您带来问题,因为
map
的签名实际上是:

final def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
因此,实际的编译器错误是:

<console>:12: error: wrong number of type parameters for method map: [B, That](f: String => B)(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Set[String],B,That])That
       strings.map[Char](_.head)
                  ^
手动提供类型参数必须如下所示:

scala> strings.map[Char, Set[Char]](_.head)
res6: Set[Char] = Set(a, d, i)

另一种绕过空字符串的方法

mySetOfStrings.flatMap(_.take(1))

另一种绕过空字符串的方法

mySetOfStrings.flatMap(_.take(1))

请注意,如果任何字符串为空,则调用
head
是不安全的。在这种情况下,您应该使用
flatMap(uu.headOption)
忽略它们。接受是因为您让我明白了我错在哪里。不过也要感谢另外两个(稍微)更快的答案。请注意,如果任何字符串为空,则调用
head
是不安全的。在这种情况下,您应该使用
flatMap(uu.headOption)
忽略它们。接受是因为您让我明白了我错在哪里。感谢另外两个(稍微)快一点的答案。
scala>Set(“foo”、“bar”和“”).map(s=>s.head)java.util.NoSuchElementException:next on empty iterator
scala>Set(“foo”、“bar”和“”).map(s=>s.head)java.util.NoSuchElementException:next on empty iterator