Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten function

Tags:

scala

The Scala docs say the flatten api flattens a list of lists and it can only be invoked on a list of lists.

Why is it possible to invoke it on the following then?

List(Some("Tony"), None).flatten  
like image 586
More Than Five Avatar asked Apr 25 '26 10:04

More Than Five


1 Answers

The ScalaDoc API shows the [use case] -- a simplified representation of the method signature. If you click on the Full signature it will expand into the complete signature:

Full Signature
def flatten[B](implicit asTraversable: (A) ⇒ GenTraversableOnce[B]): List[B]

You can call flatten on lists, or on most other collections for that matter, as long as there is an implicit conversion from the list element type A (in your case Option[String]) to a traversable of any other type.

Any Option type can be implicitly converted into a GenTraversableOnce -- Some acts as a single element collection and None as an empty collection. This means that you can call flatten on the List[Option[String]] to obtain a List[String].

like image 198
axel22 Avatar answered Apr 27 '26 23:04

axel22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!