Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First thing to note is that mutable <code>HashMap</code> is invariant: <code>class HashMap [A, B]</code>. Though the immutable version is covariant on values: <code>class HashMap [A, +B]</code>.</p> <p>Second thing to note is that your <code>repos</code> variable is meant to be a polymorphic collection which means that some compile time type information is lost when you put stuff there.</p> <p>But since you use the mutable <code>HashMap</code>, the <code>repos</code> can't actually be a correct polymorphic collection because of <code>HashMap</code> invariance. To illustrate why let's suppose Page is a class (so we can instantitate it) and we put a HashMap[String, CoolPage] in the <code>repos</code> list. Then we could do this:</p> <pre><code>val m = repos.head // HashMap[String, Page] m.put("12345678", new Page) // We just added a Page to HashMap[String, CoolPage] </code></pre> <p>So the compiler gives you an error to protect you from this.</p> <p>I guess you can fix your code by making Repository covariant:</p> <pre><code>trait Repository[+T &lt;: Page] { private[this] val pages = new HashMap[String, T] register(this) def newPage: T def apply(): T = { val page = newPage pages(page.id) = page page } def apply(id: String): T = { pages.get(id) match { case Some(page) =&gt; page.lastAccessed = new Date page case None =&gt; this() } } } </code></pre> <p>And changing <code>repos</code> to be a list of <code>Repository[Page]</code>:</p> <pre><code>private var repos: List[Repository[Page]] = Nil private def register(repo: Repository[Page]) { repos = repo :: repos } </code></pre> <p>And remember that polymorphic collections (like <code>repos</code>) make you lose compile time type information of elements: if you put a <code>Repository[CoolPage]</code> there you only get <code>Repository[Page]</code> back and have to deal with it.</p> <p><strong>update</strong>: removed <code>.asInstance[T]</code> from the <code>Repository</code> code by making <code>pages</code> <code>private[this]</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload