scala case class 这时候该怎么用
1个回答
展开全部
OK,让我们一劳永逸的解决这个问题吧,让大家见识一下Scala的强大:
给定一个字符串,自动转换为需要的case class
比如:
给定字符串"zhangsan,100,34",定义了case class Person(name: String, id: Int, age: Int),就能自动由字符串得到Person(zhangsan, 100, 34)
给定字符串"100,300,400",定义了case class Vec(x: Int, y: Int, z: Int),就能自动由字符串得到Vec(100, 300, 400)
- 首先给出最终的实现效果:
- @ case class Person(name: String, id: Int, age: Int)defined class Person@ Str2Class[Person]("ZhangSan,888,33").getres3: Person = Person("ZhangSan", 888, 33)@ case class Vec(x: Int, y: Int, z: Int)defined class Vec@ Str2Class[Vec]("100,200,300").getres5: Vec = Vec(100, 200, 300)
- 下面是具体的实现代码:
- object Str2Class {
- import util.{ Failure, Success, Try }
- trait Conveter[A] { def convert(text: String): Try[A] }
- object Conveter {
- def apply[A](implicit c: Conveter[A]): Conveter[A] = c
- implicit object s2s extends Conveter[String] {
- def convert(text: String) = Try(text)
- }
- implicit object s2i extends Conveter[Int] {
- def convert(text: String) = Try(text.toInt)
- }
- }
- import shapeless._
- trait Parser[R <: HList] { def parse(xs: Seq[String]): Try[R] }
- object Parser {
- def apply[R <: HList](implicit p: Parser[R]) = p
- def fromFun[R <: HList](f: Seq[String] => Try[R]): Parser[R] = new Parser[R] {
- def parse(xs: Seq[String]) = f(xs)
- }
- implicit object HNilParser extends Parser[HNil] {
- def parse(xs: Seq[String]): Try[HNil] = xs match {
- case Seq() => Success(HNil)
- case _ => Failure(new RuntimeException("More items than expected."))
- }
- }
- implicit def hListParser[A: Conveter, R <: HList : Parser]: Parser[A :: R] = fromFun {
- case x +: rs => for(xv <- Conveter[A].convert(x);rv <- Parser[R].parse(rs)) yield xv::rv
- case Seq() => Failure(new RuntimeException("Less items than expected."))
- }
- }
- trait LineParser[A] {
- def apply[R <: HList](text: String)
- (implicit gen: Generic.Aux[A, R], p: Parser[R]): Try[A] =
- p.parse(text.split(",")) map (gen.from)
- }
- def apply[A] = new LineParser[A]{}}
- @ import shapeless._@ import syntax.std.traversable._@ import syntax.std.tuple._@ case class data(a: Int, b: Int, c: Int, d: Int, e: Int)defined class data@ type DATA = Int :: Int :: Int :: Int :: Int :: HNildefined type DATA@ val arr = "1\t2\t3\t4\t5".split('\t').map(_.toInt)arr: Array[Int] = Array(1, 2, 3, 4, 5)
- @ val myData = data.tupled(arr.toHList[DATA].get.tupled)myData: data = data(1, 2, 3, 4, 5)
==================原回答===================
Here we go:
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询