Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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[Foo]): Option[Bar] = {
  if(myList.nonEmpty) Some(Bar(myList))
  else None
}

case class Bar(fooList: List[Foo]) {}

For some reason, my solution feels rather inelegant, and not the Scala way. It seems I should be able to use a method on List to do this sort of thing, but I can't wrap my head around it.

Is there a more Scala-like way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Option(myList).filter(_.nonEmpty).map(Bar)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...