This page is no longer maintained — Please continue to the home page at www.scala-lang.org

more about singleton types

No replies
Luc Duponcheel
Joined: 2008-12-19,
User offline. Last seen 34 weeks 3 days ago.
Hello,

singleton types are useful to support runtime linking of object based modules
(when the compiler cannot infer the correct object type)

I have tried to come up with an example that is as simple as possible
(all suggestions for simplifying it are welcome)

consider the following code

abstract class Server {
  case class Helper(kind: String)
  val helper: Helper
}

object simpleServer extends Server {
  val helper = Helper("Simple")
}

object complexServer extends Server {
  val helper = Helper("Complex")
}

abstract class Client {
  val server: Server
}

object SingletonType {
  def getRandomServer =
    if(java.lang.Math.random < 0.5)
      simpleServer
    else
      complexServer 
  def main(args: Array[String]) {
    val randomServer = getRandomServer
    object client extends Client {
      val server = randomServer
    }
    var theHelper = randomServer.helper
    theHelper = client.server.helper
  }
}

the problem with this code is that it does not compile:
the compiler cannot know (that we know) that the type Helper
of the server of the client is the same as the type Helper of
randomServer (they both have their own path dependent Helper type)

$ fsc  SingletonType.scala
/opt/home/tmp/SingletonType.scala:67: error: type mismatch;
 found   : client.server.Helper
 required: randomServer.Helper
    theHelper = client.server.helper
                              ^
one error found

the way out of this is to tell the compiler that
the server of the client has the same type as
randomServer

      val server: randomServer.type = randomServer

Luc

--
  __~O
 -\ <,
(*)/ (*)

reality goes far beyond imagination

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland