scala case class 这时候该咋用
为了回答楼主的新问题,我特意给 shapeless 发了个 Pull Request #598,现在已经合并到 shapeless 2.3.2中。
用我这个Pull Request的话,大概可以这样写:case class data(a: Int, b: String, c: String, d: Int, e: Int)val arr = line.split("\\t")val i = arr.iteratorimport shapeless._object readField extends shapeless.Poly0 { implicit def readInt = at(i.next.toInt) implicit def readString = at(i.next)}Generic.from(HList.fillWith`.Repr](readField))----------------------------------------
原问题:case class data(a: Int, b: Int, c: Int, d: Int, e: Int)val arr = line.split("\\t")data(arr(0), arr(1), arr(2), arr(3), arr(4))// 目前项目中的表非常大,如果array里面有几十个那该怎么写,请问大神们有没有更好的办法啊?原答案:
黑科技来了:case class data(a: Int, b: Int, c: Int, d: Int, e: Int)val arr = "1\\t2\\t3\\t4\\t5".split(\u0026#39;\\t\u0026#39;)val myData = https://www.zhihu.com/api/v4/questions/41977032/arr.foldLeft(data.curried) { (f, s) =/u0026gt; f.asInstanceOf(s.toInt)}.asInstanceOf 【scala case class 这时候该咋用】 注意,本代码纯属娱乐,写得很污,请勿模仿!
■网友
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("ZhangSan,888,33").getres3: Person = Person("ZhangSan", 888, 33)@ case class Vec(x: Int, y: Int, z: Int)defined class Vec@ Str2Class("100,200,300").getres5: Vec = Vec(100, 200, 300)下面是具体的实现代码:object Str2Class { import util.{ Failure, Success, Try } trait Conveter { def convert(text: String): Try } object Conveter { def apply(implicit c: Conveter): Conveter = c implicit object s2s extends Conveter { def convert(text: String) = Try(text) } implicit object s2i extends Conveter { def convert(text: String) = Try(text.toInt) } } import shapeless._ trait Parser { def parse(xs: Seq): Try } object Parser { def apply(implicit p: Parser) = p def fromFun(f: Seq =\u0026gt; Try): Parser = new Parser { def parse(xs: Seq) = f(xs) } implicit object HNilParser extends Parser { def parse(xs: Seq): Try = xs match { case Seq() =\u0026gt; Success(HNil) case _ =\u0026gt; Failure(new RuntimeException("More items than expected.")) } } implicit def hListParser: Parser = fromFun { case x +: rs =\u0026gt; for(xv \u0026lt;- Conveter.convert(x);rv \u0026lt;- Parser.parse(rs)) yield xv::rv case Seq() =\u0026gt; Failure(new RuntimeException("Less items than expected.")) } } trait LineParser { def apply(text: String) (implicit gen: Generic.Aux, p: Parser): Try = p.parse(text.split(",")) map (gen.from) } def apply = new LineParser{}}
推荐阅读
- 环球车讯网|奔驰X-Class特别版发布,来自波兰改装厂的大手笔
- 趣头条|吸睛之作 梅赛德斯·奔驰X-Class推改装特别版 全车采用大量碳纤维
- 后视镜|全车碳纤维 梅赛德斯-奔驰X-Class特别版发布
- 网通社|波兰改装厂打造 全车内外碳纤维 梅赛德斯-奔驰 X-Class特别版
- Python中怎样在list中保存class类型的数据
- iPad Air Smart Case 值得购买吗
- 技术选型:golang, nodejs, scala, java, .net core. 那个好
- 用classpass模式做美发O2O可行吗?
- 奔驰|科技智能 梅赛德斯奔驰S-Class自动泊车
- class里面有空格的元素咋选择
