官术网_书友最值得收藏!

Products can report the names of their element

This feature probably will be mostly useful for the case classes as it makes possible some generic programming without the need to resort to reflection or macros. 

The following examples demonstrate how the new productElementName(idx) method can be used to build a naive JSON serializer for simple case classes:

case class User(name: String, surname: String, email: String)

def naiveToJsonString(p: Product): String =
(for { i <- 0 until p.productArity } yield
s""""${p.productElementName(i)}": "${p.productElement(i)}"""")
.mkString("{ ", ", ", " }")

Obviously, this simple iteration does not take nesting and escaping into account, but it already can produce valid results in elementary cases:

scala> val user = User("John", "Doe", "jd@mail.me")
user: User = User(John,Doe,jd@mail.me)
scala> naiveToJsonString(user)
res1: String = { "name": "John", "surname": "Doe", "email": "jd@mail.me" }

Unfortunately, the method taking an index of the element throws an exception in the case that the index is invalid:

scala> user.productElementName(3)
java.lang.IndexOutOfBoundsException: 3
at User.productElementName(<console>:1)
... 38 elided

We will discuss why throwing exceptions is not the best approach, as well as viable alternatives, in Chapter 6, Exploring Built-In Effects.

主站蜘蛛池模板: 随州市| 邯郸市| 甘德县| 邵武市| 丹阳市| 上虞市| 金堂县| 保靖县| 建始县| 岢岚县| 临高县| 邵阳县| 阿尔山市| 西和县| 天门市| 新河县| 冀州市| 蒙山县| 鄂尔多斯市| 集贤县| 监利县| 深水埗区| 大邑县| 乐都县| 丰原市| 应城市| 蓝田县| 石柱| 东宁县| 泌阳县| 曲靖市| 康乐县| 皋兰县| 高雄市| 咸丰县| 民县| 镇平县| 宁远县| 封开县| 阿克陶县| 张家口市|