Min/max with Option[T] for possibly empty Seq?

后端 未结 10 986
别那么骄傲
别那么骄傲 2021-01-31 14:03

I\'m doing a bit of Scala gymnastics where I have Seq[T] in which I try to find the \"smallest\" element. This is what I do right now:

val leastOrNo         


        
10条回答
  •  逝去的感伤
    2021-01-31 14:29

    Starting Scala 2.13, minByOption/maxByOption is now part of the standard library and returns None if the sequence is empty:

    seq.minByOption(_.something)
    
    List((3, 'a'), (1, 'b'), (5, 'c')).minByOption(_._1) // Option[(Int, Char)] = Some((1,b))
    List[(Int, Char)]().minByOption(_._1)                // Option[(Int, Char)] = None
    

提交回复
热议问题