当我在 scala 中使用 flatMap 时显示此错误

when I use flatMap in scala show this error

这是我的代码

def createList(num: Int) = {
  num to num + 10
}
Some(1).flatMap(createList)

在编译器之后,它显示单词:错误:类型不匹配

我知道

Some(1).toSeq.flatMap(createList) 
or
Some(1).flatMap(Some(createList))

能对

如果我用这个也可以:

def createBox(a: Int) = Box(Some(a)
Some(1).flatMap(createBox)

documention 中看到隐含的 Box2Option,这是有效的吗

Box 是来自 liftWeb frameWork 的类型

Option#flatMapacceptsA => Option[B],不是A => Seq[B].

试试这个:

Some(1).toSeq.flatMap(createList)

您的 createList 函数应将其结果包装在一个选项中(因为您是在一个选项上调用 flatMap)。或者,您可以只使用 map 而不是 flatMap,您的函数就可以正常工作。实际上,您期望结果如何? Option 还是 Seq?