0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Scala] typesafe config で取得したデータを扱いやすくする

Posted at

typesafe config については こちら の方が超わかりやすく書いていただいているのでこちらを参照

で、 typesafe config で取得したファイルは javaの型で返ってくるのでかなり扱いづらいです

以下のデータを取得して、sampleListをループで回したいとします

application.cong
sampleList = [
  {
    id = 1
    name = "mike"
    sex = 1
    age = 24
  },
  {
    id = 2
    name = "neko"
    sex = 0
    age = 31
  },
  {
    ...
]

そのまま取得しただけではmapが使えないので、 toArray をして上げる必要があります

    config.getConfigList("sampleList").toArray.map(
      x => println(x)
    )

### output
Config(SimpleConfigObject({"id":1,"name":"mike","sex":1,"age":24}))
Config(SimpleConfigObject({"id":2,"name":"neko","sex":0,"age":31}))

ここから中身を取得したいのですが、うまくいきません

    config.getConfigList("sampleList").toArray.map(
      x => println(x.getInt("Id"))
    )

### エラーメッセージ
cannot resolve symble getInt

Scalaで扱いやすい型に変換するために、 asScala を使います

import scala.collection.JavaConverters._

    config.getConfigList("sampleList").asScala.map(
      x => println(x)
    )

### output
Config(SimpleConfigObject({"id":1,"name":"mike","sex":1,"age":24}))
Config(SimpleConfigObject({"id":2,"name":"neko","sex":0,"age":31}))

出力される値は同じなのですが、 get~~が使えるようになるため簡単に中身が取得できます。

    config.getConfigList("sampleList").asScala.map(
      x => println(
          x.getInt("id"),
          x.getString("name"),
          x.getInt("sex"),
          x.getInt("age"),
      )
    )

### output
(1,"mike",1,24)
(2,"neko",0,31)

configから配列などを受け取る場合はこちらがよさそうです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?