Scala:有一种通用的方法来修剪案例类的所有String字段吗?

前端之家收集整理的这篇文章主要介绍了Scala:有一种通用的方法来修剪案例类的所有String字段吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一种通用的方法(例如某些函数),它接受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,3)

猜你在找的Scala相关文章