views:

172

answers:

1

Hi, I don't know if a solution exists but it would be highly desirable.

I'm making a Scala Applet, and I want the main Applet class to be a singleton so it can be accessed elsewhere in the applet, sort of like:

object App extends Applet {
  def init {
    // do init here
  }
}

Instead I have to make the App class a normal instantiatable class otherwise it complains because the contructor is private. So the ugly hack I have is to go:

object A {
  var pp: App = null
}

class App extends Applet {
  A.pp = this
  def init {
    // do init here
  }
}

I really hate this, and is one of the reasons I don't like making applets in Scala right now.

Any better solution? It would be nice...

edit -- I found a pretty decent hack solution using implicit conversion. Declare your Applet class as a normal class, and then add:

class Appable {}

object App extends Appable {
implicit def appable2App(a:Appable) = inst
  var inst: App = null
}

Then just set the instance variable when the Applet is created, and you can access everything as if it were a singleton.

+2  A: 

What you're asking for is counter to the applet execution model. Specifically, there are no guarantees that you won't have multiple copies of the applet running in the same JVM. The default is to run every applet in the same JVM (including multiple copies of the same applet if necessary). See e.g. Sun's tutorial.

That's why applets are specified the way that they are instead of with a static public void method. Can't the rest of your code take the applet as a parameter?

Rex Kerr
Wow, that explains the crazy behavior I've been getting. It means that you can't use any singletons that have any side effects when using an applet. I think it also means I probably won't use Scala for an applet ever again. Thanks for the response.
nullspace
In that case, don't use Java or any other JVM language either. It's the same model, you know!
Rex Kerr
Yeah that occurred to me after, lol. I guess static objects are just not meant to work with the browser's environment. It's ok though, I can just run from a jar when I need two instances on one computer.
nullspace