How to make method return the same generic as the input?

前端 未结 3 1034
面向向阳花
面向向阳花 2021-02-07 10:20

I want to split a string delimited by commas and use the result as either a Seq or a Set:

def splitByComma(commaDelimited: String): Arr         


        
3条回答
  •  孤街浪徒
    2021-02-07 10:45

    @KrzysztofAtłasik's answer works great for Scala 2.12.
    This is a solution for 2.13. (Not completely sure if this is the best way).

    import scala.collection.Factory
    import scala.language.higherKinds
    
    def splitByComma[C[_]](commaDelimited: String)(implicit f: Factory[String, C[String]]): C[String] =
      f.fromSpecific(commaDelimited.split(","))
      // Or, as Dmytro stated, which I have to agree looks better.
      commaDelimited.split(",").to(f)
    

    Which you can use like this:

    splitByComma[Array]("hello,world!")
    // res: Array[String] = Array(hello, world!)
    
    splitByComma[Set]("hello,world!")
    // res: Set[String] = Set(hello, world!)
    
    splitByComma[List]("hello,world!")
    // res: List[String] = List(hello, world!)
    

提交回复
热议问题