How to compose functions that return Option[List] in Scala?

前端 未结 2 1821
我在风中等你
我在风中等你 2021-01-01 07:26

Suppose I have two functions to get orders and order items:

def getOrders(): Option[List[Int]] = ...
def getOrderItems(orderId: Int): Option[List[Int]] = ...
         


        
2条回答
  •  余生分开走
    2021-01-01 07:33

    The simplest modification I could think of is as below:

    for{
        orderId <- getOrders.getOrElse(Nil)
        items <- getOrderItems(orderId)
    } yield items
    

    The for comprehension uses the first statement to determins the rest the types. For instance in the above the type List[Int] would be infered and this is different from Option[List[Int]].

提交回复
热议问题