我需要一种通用方法(例如某些函数),它接受 case 类(任何类型)的实例并返回此实例的副本,但带有修剪过的字符串。
(最好没有反射)
任何的想法?
最佳答案
您可以使用 shapeless去做这个:
import shapeless._
import shapeless.ops.hlist._
// Trims if passed a String value, otherwise returns the value unchanged
object Trimmer extends Poly1 {
implicit val stringTrim = at[String] { _.trim }
implicit def noop[T] = at[T] { identity }
}
// Uses a Generic to transform the instance into an HList, maps over it
// and convert it back into the case class
def trimCaseClass[C, H <: HList](c: C)
(implicit g: Generic.Aux[C, H], m: Mapper.Aux[Trimmer.type, H, H]): C = {
val hlist = g.to(c)
val trimmed = hlist.map(Trimmer)
g.from(trimmed)
}
然后:
scala> case class A(s1: String, s2: String, i: Int)
defined class A
scala> val a = A(" 1 ", "2", 3)
a: A = A( 1 ,2,3)
scala> trimCaseClass(a)
res0: A = A(1,2,3)
关于Scala:是否有一种通用的方法来修剪案例类的所有 String 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885976/