- Learn Scala Programming
- Slava Schmidt
- 150字
- 2021-06-10 19:35:39
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.
推薦閱讀
- Python高級(jí)編程
- DevOps Automation Cookbook
- C/C++常用算法手冊(cè)(第3版)
- C語(yǔ)言程序設(shè)計(jì)案例式教程
- Monitoring Elasticsearch
- 軟件項(xiàng)目管理實(shí)用教程
- Learning Data Mining with R
- UML 基礎(chǔ)與 Rose 建模案例(第3版)
- 學(xué)習(xí)OpenCV 4:基于Python的算法實(shí)戰(zhàn)
- PLC應(yīng)用技術(shù)(三菱FX2N系列)
- HTML5從入門(mén)到精通(第4版)
- 代替VBA!用Python輕松實(shí)現(xiàn)Excel編程
- Building Dynamics CRM 2015 Dashboards with Power BI
- Unity Android Game Development by Example Beginner's Guide
- 輕松學(xué)Scratch 3.0 少兒編程(全彩)