Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

scala - Why can I not flatMap a List[Option] using underscore?

Why can I write

val flat: List[Int] = List(Some(1), Some(2)).flatMap(i => i)

But not

val flat: List[Int] = List(Some(1), Some(2)).flatMap(_)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The underscore is a placeholder for a variable. It's not, in and of itself, a function. flatMap requires a function.

Also, in this case, there is a flatten method which is defined on List for which Option has within the Predef an implicit conversion such that what you've written can be condensed into just that call, List(Some(1)).flatten


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...