Map versus FlatMap on String

后端 未结 5 1661
无人共我
无人共我 2020-12-02 16:12

Listening to the Collections lecture from Functional Programming Principles in Scala, I saw this example:

scala> val s = \"Hello World\"

scala> s.flat         


        
5条回答
  •  萌比男神i
    2020-12-02 16:23

    Use flatMap in situations where you run map followed by flattern. The specific situation is this:

    • You’re using map (or a for/yield expression) to create a new collection from an existing collection.

    • The resulting collection is a List of Lists.

    • You call flatten immediately after map (or a for/yield expression).

    When you’re in this situation, you can use flatMap instead.

    Example: Add all the Integers from the bag

    val bag = List("1", "2", "three", "4", "one hundred seventy five")
    
    def toInt(in: String): Option[Int] = {
    try {
    Some(Integer.parseInt(in.trim))
    } catch {
    case e: Exception => None
    }
    }
    

    Using a flatMap method

    > bag.flatMap(toInt).sum
    

    Using map method (3 steps needed)

    bag.map(toInt) // List[Option[Int]] = List(Some(1), Some(2), None, Some(4), None)
    
    bag.map(toInt).flatten //List[Int] = List(1, 2, 4)
    
    bag.map(toInt).flatten.sum //Int = 7
    

提交回复
热议问题