Marais Rossouw
Marais Rossouw

Reputation: 957

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;}]
}

Upvotes: 0

Views: 157

Answers (1)

gzm0
gzm0

Reputation: 14842

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]]
}

Upvotes: 3

Related Questions