本文介绍了如何使方法返回与输入相同的泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分割一个用逗号分隔的字符串,并将结果用作 Seq Set :

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

def splitByComma(commaDelimited: String): Array[String]
  = commaDelimited.trim.split(',')

def splitByCommaAsSet(commaDelimited: String): Set[String]
  = splitByComma(commaDelimited).toSet

def splitByCommaAsSeq(commaDelimited: String): Seq[String]
  = splitByComma(commaDelimited).toSeq

val foods = "sushi,taco,burrito"
val foodSet = splitByCommaAsSet(foods)
// foodSet: scala.collection.immutable.Set[String] = Set(sushi, taco, burrito)
val foodSeq = splitByCommaAsSeq(foods)
// foodSeq: Seq[String] = List(sushi, taco, burrito)

但是,这是相当重复的.理想情况下,我希望有一个类似 genericSplitByComma [Set](foods)的东西,当我传入 Set 并返回时,它只返回一个 Set 当我通过 Seq 时是一个 Seq .

However, this is quite repetitive. Ideally, I would want to have something like genericSplitByComma[Set](foods) that just returns a Set when I pass Set in, and returns a Seq when I pass Seq.

推荐答案

@KrzysztofAtłasik的答案非常适合 Scala 2.12 .
这是 2.13 的解决方案.(不确定是否是最好的方法).

@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)

您可以这样使用:

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!)

这篇关于如何使方法返回与输入相同的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:52