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

  • 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.

主站蜘蛛池模板: 阳江市| 双峰县| 武义县| 温州市| 新丰县| 石台县| 田东县| 岳池县| 大石桥市| 松滋市| 安宁市| 毕节市| 河池市| 龙海市| 海口市| 英山县| 武城县| 泰宁县| 通榆县| 科技| 万源市| 屏东市| 汝南县| 泽州县| 张家界市| 西乡县| 襄垣县| 任丘市| 高尔夫| 呼伦贝尔市| 宣恩县| 宁明县| 东明县| 舞钢市| 普陀区| 平度市| 丰台区| 织金县| 景宁| 怀化市| 涟水县|