OK,让我们一劳永逸的解决这个问题吧,让大家见识一下Scala的强大:
比如:
给定字符串"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]{}}
==================原回答===================
Here we go:
@ 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)
没有tuple1scala>val t2=("test",1)
t2: (String, Int) = (test,1)
scala>t2.getClass
res0: Class[_ <: (String, Int)] = class scala.Tuple2
scala>val t3=("ok",12,100.0)
t3: (String, Int, Double) = (ok,12,100.0)
scala>t3.getClass
res1: Class[_ <: (String, Int, Double)] = class scala.Tuple3
tuple就是用来把几个数据放在一起的比较方便的方式,上面的例子定义了一个tuple2和一个tuple3,区别就是tuple2放两个数据、tuple3放3个数据。好像最大是tuple21
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)