How does Scala's groupBy identity work?

后端 未结 6 1050
天涯浪人
天涯浪人 2021-02-01 05:56

I was browsing around and found a question about grouping a String by it\'s characters, such as this:

The input:

\"aaabbbccccdd\"
         


        
6条回答
  •  花落未央
    2021-02-01 06:42

    Whenever you try to use methods such as groupBy on the String. It's important to note that it is implicitly converted to StringOps and not List[Char].

    StringOps

    The signature of groupBy is given by-

    def groupBy[K](f: (Char) ⇒ K): Map[K, String]
    

    Hence, the result is in the form -

    Map[Char,String]
    

    List[Char]

    The signature of groupBy is given by-

    def groupBy[K](f: (Char) ⇒ K): Map[K, List[Char]]
    

    If it had been implicitly converted to List[Char] the result would be of the form -

    Map[Char,List[Char]]
    

    Now this should implicitly answer your curious question, as how scala figured out to groupBy on Char (see the signature) and yet give you Map[Char, String].

提交回复
热议问题