Incerteza
Incerteza

Reputation: 34884

Use nullable instead of Option?

I have singleton:

class MySing private (var1: SomeType) { ... }
object MySing {

  @volatile
  private var instance: Option[MySing] = None

  def apply(var1: SomeType): Option[MySing] = {
    if (instance.isEmpty) {
      this.synchronized {
        if (instance.isEmpty) instance = Some(new MySing(var1))
      }
    }

    instance
  }
}

So whenever I want to get an instance of it, I have to use either get or pattern matching

MySing(myVar1) match {
  case Some(x) => ...
  case None =>
}

or

MySing(myVar1).get

Even Scala encourages using Option, won't it be reasonable in my case not to use it to get rid of boring, redundant operations I've shown above?

object MySing {

  @volatile
  private var instance: MySing = null

  def apply(var1: SomeType): MySing = {
    if (instance == null) {
      this.synchronized {
        if (instance == null) instance = new MySing(var1)
      }
    }

    instance
  }
}

Upvotes: 2

Views: 472

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

Returning Option[MySing] implies that you may not return a value (i.e. returning None) from apply, but I don't see how this makes sense. You are always returning an instance from apply, so you can get ride of the Option in the return type, with something like this

class MySing private (val var1: String)
object MySing {

  @volatile
  private var instance: Option[MySing] = None

  def apply(var1: String): MySing = {
    instance getOrElse {
      this.synchronized {
        instance.getOrElse {
         instance = Some(new MySing(var1))
         instance.get
        }
      }
    }
  }
}

Usage example

scala> val x = MySing("hello")
x: MySing = MySing@232b0a52

scala> x.var1
res0: String = hello

scala> val y = MySing("hola")
y: MySing = MySing@232b0a52

scala> y.var1
res1: String = hello // are you sure this is sensible?

However, it still looks kind of ugly: you're creating a singleton with a parameter, consequently ignoring every argument passed to the apply method after the first invocation. Ugh!

You may want to rethink your design (and forget about null)

Upvotes: 2

Related Questions