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

标签 scala trim case-class

我需要一种通用方法(例如某些函数),它接受 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/

相关文章:

scala - 将字符串重定向到 scala.sys.process

ScalaTest 和 SBT : Reporting progress of test suite?

macos - Mac OS Intellij 运行 scala 程序时出错

scala - 在 Scala 中将条件转换为选项

android - Android 应用程序中的修剪视频功能

java - Spring StringTrimmerEditor 取消字段而不是禁止

在 n 个字符后 trim 的 JavaScript

scala - 等于具有浮点字段的 case 类

scala - 依靠特征中的案例类方法

scala - 自动散列 Consed 案例类