Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneralized structural type conformance in Scala
    primarykey
    data
    text
    <p>I'm interested in the problem of conforming a specific type to a more general structural type. Consider the following examples:</p> <pre><code>trait Sup trait Sub extends Sup type General = { def contra(o: Sub): Unit def co(): Sup def defaults(age: Int): Unit def defaults2(age: Int): Unit def defaults3(first: String): Unit } trait Specific { def contra(o: Sup): Unit // doesn't conform def co(): Sub // conforms def defaults(age: Int, name: String = ""): Unit // doesn't conform def defaults2(name: String = "", age: Int = 0): Unit // doesn't conform def defaults3(first: String = "", last: String = ""): Unit // doesn't conform } </code></pre> <p>In each of the non-conforming cases, a call to the method in <code>General</code> can safely be resolved to the corresponding method in <code>Specific</code>. A more interesting practical example can be found in <a href="https://stackoverflow.com/questions/3459630/scala-immutable-objects-and-traits-with-val-fields">this question</a>:</p> <pre><code>trait Versionable[T] { self: { def copy(version: Int): T } =&gt; val version = 0 def incrementVersion = copy(version = version + 1) } case class Customer(name: String, override val version: Int) extends Versionable[Customer] { def changeName(newName: String) = copy(name = newName) } </code></pre> <p>Here, the Customer's <code>copy</code> method does not conform to the signature in Versionable's self-type annotation. Note, however, that if the compiler allowed, <code>copy</code> could be invoked just as it is in <code>Versionable.incrementVersion</code>. Clearly, the actual signature of Customer's <code>copy</code> method is too specific for use in Versionable, since it carries the irrelevant knowledge that one can optionally supply a <code>name</code> parameter.</p> <p>Are there ways to work around these limitations? Are there reasons that such generalized conformance would be a bad idea?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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