Search code examples
scalacollectionstype-safety

How to know if a List is homogeneous


I want to know if a List is homogeneous.

Here is my code :

def isHomogeneous(ls: List[Any]) = ls.map(_.getClass).toSet.size == 1

Is there a better way ?


Solution

  • def allEqual(xs: Traversable[_]) =
      xs.headOption.forall(head => xs.forall(_ == head))
    
    def isHomogeneous(xs: Traversable[_]) =
      allEqual(xs.view.map(_.getClass))
    
    • Keeps the getClass business separate from the traversal.
    • Uses more general type Traversable instead of List.
    • Works for Nil.
    • Does not traverse the entire collection unless necessary.