Skip to content

Instantly share code, notes, and snippets.

@fare
Created December 22, 2016 03:43
Show Gist options
  • Save fare/7620f8fd2708feedcec3bc5d8863eb9c to your computer and use it in GitHub Desktop.
Save fare/7620f8fd2708feedcec3bc5d8863eb9c to your computer and use it in GitHub Desktop.
Context passing in Scala
trait IsContext {
def contextualContent: List[HasContext[this.type]] = List()
contextualContent.map { item => item.setContext(this) }
}
trait HasContext[+Context] {
private var ctx: Any = null
def setContext(context: Any) {
assert(ctx == null)
ctx = context
}
lazy val context = ctx.asInstanceOf[Context]
}
trait Contextual[+Context] extends IsContext with HasContext[Context]
@fare
Copy link
Author

fare commented Dec 24, 2016

Better, just pass along values in mutual recursive definitions:

object simpleContext {

  trait HasContext[+Context] {
    has =>
    def context: Context
    trait ThisContext extends HasContext[Context] {
      def context = has.context
    }
  }
  trait IsContext[+Context] extends HasContext[Context] {
    this: Context =>
    override def context: this.type = this
  }

  // Using it...
  trait Page {
    def show () : Unit
  }

  trait User {
    val name : String
  }
  trait UserContext extends IsContext[UserContext] {
    val user : User
    val mainPage : Page
  }
  trait HelloPage extends Page with HasContext[UserContext] {
    def show () = println("Hello, " + context.user.name)
  }
  val ctx1 = new UserContext {
    val user = new User { val name = "Alice" }
    val mainPage = new HelloPage with ThisContext
  }

  // Refining it...
  trait Player extends User {
    var points : Int
  }
  trait PlayerContext extends IsContext[PlayerContext] with UserContext {
    val user: Player
  }
  trait ScorePage extends HelloPage with HasContext[PlayerContext] {
    override def show () = {
      super.show ()
      println("You have " + context.user.points + " points")
    }
  }
  val ctx2 = new PlayerContext {
    ctx =>
    val user = new Player {
      val name = "Bob"
      var points = 99
    }
    val mainPage = new ScorePage with ThisContext
  }
  def main(args: Array[String]): Unit = {
    ctx1.mainPage.show()
    ctx2.mainPage.show()
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment