scala – 为什么选项需要显式的toList里面的循环?
发布时间:2020-12-16 09:17:50 所属栏目:安全 来源:网络整理
导读:使用for循环与一个简单的选项工作: scala for (lst - Some(List(1,2,3))) yield lstres68: Option[List[Int]] = Some(List(1,3)) 但是循环选项的内容不是: scala for (lst - Some(List(1,3)); x - lst) yield xconsole:8: error: type mismatch; found : L
使用for循环与一个简单的选项工作:
scala> for (lst <- Some(List(1,2,3))) yield lst res68: Option[List[Int]] = Some(List(1,3)) 但是循环选项的内容不是: scala> for (lst <- Some(List(1,3)); x <- lst) yield x <console>:8: error: type mismatch; found : List[Int] required: Option[?] for (lst <- Some(List(1,3)); x <- lst) yield x ^ …除非该选项明确转换为列表: scala> for (lst <- Some(List(1,3)).toList; x <- lst) yield x res66: List[Int] = List(1,3) 为什么需要显式列表转换?这是惯用的解决方案吗? 解决方法for (lst <- Some(List(1,3)); x <- lst) yield x 被翻译成 Some(List(1,3)).flatMap(lst => lst.map(x => x)) OptionA上的flatMap方法需要一个返回一个Option的函数,但是你传递一个返回List的函数,并且没有从List到Option的隐式转换. 现在,如果您首先将Option转换为列表,那么将会调用List的flatMap方法,这样会返回一个返回List的函数,这就是你传递给它的一个函数. 在这种特殊情况下,我认为最惯用的解决方案是 Some(List(1,3)).flatten.toList (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |