Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact syntax for get head of list as Option

Is there a compact way to get the head of a list as a Some when the list is non-empty, getting None otherwise?

This is what I am currently doing,

val ms = moves.filter { ...some predicate... }
if (ms.nonEmpty) Some(ms.head) else None
like image 997
Janek Bogucki Avatar asked Jan 22 '13 21:01

Janek Bogucki


1 Answers

Try headOption. The API docs are your friend.

Note also that find does exactly a filter plus headOption: it takes one item if there and puts it in an option, and otherwise gives None.

like image 108
Rex Kerr Avatar answered Sep 22 '22 06:09

Rex Kerr