BiasedScala: Initializing without new
王福强
In the old days, when we want to create some instances of some classes, we have to use the new
keyword, just like this:
val payloadOldWay = new JsonObject();
val message = new JsonObject
It’s not a big deal in the most of the time, but when Scala3 comes, the new
keyword is not mandatory anymore, I think it’s a small change BUT a big step, less keystrokes matter:
val payload = JsonObject()
Underneatch, Scala3 compiler will take care of the old new
things, this time, scala team leave simple to user and leave complexity to themselves.
The most beautiful thing with this feature is that it makes method chaining easier:
val payload = JsonObject()
.put("apiUser","xyz")
.put("apiKey","xxx")
.put("message", JsonObject().put("text", "Hello world!"))
// of course, most of the time, I just write above code in one-liner:
// val payload = JsonObject().put("apiUser","xyz").put("apiKey","xxx").put("message", JsonObject().put("text", "Hello world!"))
As a vertx json API user, I like this feature very much ;)
I am old fashioned, so simple json libray which is easy to understand like vertx is my favorite, I don’t like marshalling/unmarshalling with other libraries with reflection or other meta programming tricks.
欢迎加入「福强私学」
跨越2190个日夜,始终坚持“实践 + 原创”打造的715125字专属知识库,囊括了(但不限于)从职场、技术、管理与商业等多个板块的内容。
- 一个ChatGPT触达不到的地方
- 一个带你超越AI/人工智能的地方
- 一个与你一起成长的地方
开天窗,拉认知,订阅「福报」,即刻拥有自己的全模态人工智能。