書名: 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.
推薦閱讀
- Spring 5.0 Microservices(Second Edition)
- Python編程自學手冊
- 基于粒計算模型的圖像處理
- Android應用程序開發與典型案例
- Kibana Essentials
- 前端跨界開發指南:JavaScript工具庫原理解析與實戰
- Mastering Objectoriented Python
- CentOS 7 Linux Server Cookbook(Second Edition)
- Visual C++數字圖像模式識別技術詳解
- VMware虛擬化技術
- 深入淺出PostgreSQL
- bbPress Complete
- Visual Basic程序設計
- C#程序設計教程(第3版)
- Hands-On JavaScript for Python Developers