Convert a List into an Option if it is populated

前端 未结 5 1885
北荒
北荒 2020-12-15 20:55

I have a method that should convert a list to an Option of an object, or None if the list is empty.

def listToOption(myList: List[F         


        
相关标签:
5条回答
  • 2020-12-15 21:06

    Lee's answer is good, but I think this corresponds to the intention a bit more clearly:

    Option(myList).filter(_.nonEmpty).map(Bar)
    
    0 讨论(0)
  • 2020-12-15 21:15
    import scalaz._; import Scalaz._
    myList.toNel.map(Bar)
    

    toNel - is "to non-empty list" here, it returns Option[NonEmptyList] for safety:

    scala> case class Bar(a: NonEmptyList[Int])
    defined class Bar
    
    scala> List(1,2,3).toNel.map(Bar)
    res64: Option[Bar] = Some(Bar(NonEmptyList(1, 2, 3)))
    
    scala> List[Int]().toNel.map(Bar)
    res65: Option[Bar] = None
    
    0 讨论(0)
  • 2020-12-15 21:16
    myList.headOption.map(_ => Bar(myList))
    
    0 讨论(0)
  • 2020-12-15 21:17

    How about:

    Some(myList) collect { case(l@hd::tl) => Bar(l) }
    

    Seems pretty scala-esque to me.

    0 讨论(0)
  • 2020-12-15 21:19

    Starting Scala 2.13, Option has a when builder:

    Option.when(condition)(result)
    

    which in our case gives:

    Option.when(myList.nonEmpty)(Bar(myList))
    // val myList = List[Int]()    =>    Option[Bar] = None
    // val myList = List(1, 2)     =>    Option[Bar] = Some(Bar(List(1, 2)))
    

    Also note Option.unless which promotes the opposite condition:

    Option.unless(myList.isEmpty)(Bar(myList))
    // val myList = List[Int]()    =>    Option[Bar] = None
    // val myList = List(1, 2)     =>    Option[Bar] = Some(Bar(List(1, 2)))
    
    0 讨论(0)
提交回复
热议问题