Marais Rossouw Marais Rossouw - 3 months ago 23
Scala Question

Nested traits / facade in Scala

If you take a look at the Reddit api you get back something like this:

{"children": [{"data":{"permalink": "a", "url": "b", "etc": "..."}}]


How would I define a Scala trait that represents that?

Something along these lines maybe...?

trait RedditSubreddit extends js.Object {
val children: Array[trait {val permalink: String; val url: String;}]
}

Answer

I'd do it like this.

trait RedditPost extends js.Object {
  val permalink: String
  val url: String
}

trait RedditSubreddit extends js.Object {
  val children: js.Array[RedditPost]
}

Although, given that Reddit allows arbitrary nesting of sub-posts, the API might more correspond to this:

trait RedditPost extends js.Object {
  val permalink: String
  val url: String
  val children: js.Array[RedditPost]
}

Or maybe you want to add an UndefOr in case the field is not always set:

trait RedditPost extends js.Object {
  val permalink: String
  val url: String
  val children: js.UndefOr[js.Array[RedditPost]]
}
Comments