简体   繁体   中英

scala abstract type parameterized by `this.type`

Im trying to create Script and ScriptType classes. ScriptType s would produce Script s of a particular abstract type. Script s would be parameterized by the ScritpType that created them.

My first attempt looked like this:

trait Script[Type <: ScriptType]

sealed trait ScriptType {
  type S <: Script[this.type]
}

object ScriptType {
  class Scala extends ScriptType {
    type S = ScalaScript
  }
}

import ScriptType._

case class ScalaScript(source: String) extends Script[Scala]

but im getting a error in compilation regarding the assigning of type S in ScriptType.Scala

Error:(10, 10) overriding type S in trait ScriptType with bounds <: Script[Scala.this.type];
  type S has incompatible type
  type S = ScalaScript

in this example is ScalaScript not a Script[Scala.this.type] ?

ScalaScript is not a Script[Scala.this.type] , since this.type means a singleton type that's unique for each Scala instance.

You can solve this by making Script contravariant:

trait Script[-Type <: ScriptType]

so that ScalaScript can be accepted as a subtype of Script[Scala.this.type] , since Scala is a supertype of Scala.this.type (the singleton type of any instance of Scala ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM