Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9180671
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T18:06:43+00:00 2026-06-17T18:06:43+00:00

I know there are multiple questions addressing related problems, but I’m not sure it

  • 0

I know there are multiple questions addressing related problems, but I’m not sure it does attack exactly what I’m looking for. I’m still new to Scala, after several years of Java development. I’m looking for the best way to test if an object has been initialized, and if not, initialize it then. For example, in Java:

private MyObject myObj = null;

and at some point in the future:

public void initMyObj(){
    if (myObj == null){
        myObj = new MyObj();
    }
    // do something with myObj
}

After this, I might reassign myObj to a different object, but it is unlikely. In Scala, I have this:

class Test {
    var myObj: MyObj = _
}

I’ve read that I could use Option instead, something like:

var myObj = None : Option[MyObj]

and then my check:

myObj match {
  case None => ...
  case Some(value) => ...
}

but it feels ackward to use this pattern when I might not make this kind of check anywhere else at any other time – though being so new to Scala, I might be wrong. Is this the best way to achieve what I want or is there any other option not involving Option?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T18:06:44+00:00Added an answer on June 17, 2026 at 6:06 pm

    It is not generally ideal practice in Scala to leave partially-constructed objects lying around. You would normally rethink how your objects were getting instantiated to see if you can’t use a different pattern that is less fragile. For example, instead of setting uninitialized variables in methods:

    class Foo { var a: String = null; var b: String = null }
    def initFooA(s: String, f: Foo) { if (f.a == null) f.a = s }
    def initFooB(s: String, f: Foo) { if (f.b == null) f.b = s }
    f
    initFooA("salmon", f)
    // Do stuff
    initFooB("herring", f)
    

    you would attempt to restructure your code to generate the values you need on demand, and delay the instantiation of foo until then:

    case class Bar(a: String, b: String) {}
    def initBarA(s: String) = s
    def initBarB(s: String) = s
    val iba = initBarA("halibut")
    // Do stuff
    val ibb = initBarB("cod")
    Bar(iba, ibb)
    

    Because Scala has easy access to tuples (and type inference), this can be a lot less painful than in Java.

    Another thing you can do is defer the late initialization to someone else.

    case class Baz(a: String)(bMaker: => String) {
      lazy val b = bMaker
    }
    

    Now you pass in something that will make parameter b, and arrange for it to handle any late initialization stuff that needs to be handled. This doesn’t always avoid needing to set vars, but it can help push it out of your class code into your initialization logic (which is usually a better place for it).

    Doing this with vars is a little less straightforward. Realistically, you’re probably best off just devoting a class to it e.g. by:

    class LazyVar[A](initial: => A) {
      private[this] var loaded = false
      private[this] var variable: A = _
      def apply() = { if (!loaded) { loaded = true; variable = initial }; variable }
      def update(a: A) { loaded = true; variable = a }
    }
    

    where you then (sadly) have to use () on every read and write.

    scala> val lv = new LazyVar({ println("Hi!"); 5 })
    lv: LazyVar[Int] = LazyVar@2626ea08
    
    scala> lv()
    Hi!
    res2: Int = 5
    
    scala> lv() = 7
    
    scala> lv()
    res4: Int = 7
    

    Then you use an instance of this class instead of the actual var and pass through the lazy initializer. (lazy val is very much like this under the hood; the compiler just protects you from noticing.)

    Finally, if you want to have a fully-functional object that is occasionally missing a value, var x: Option[X] is the construct you want to use; if you can’t find a way around the standard Java creation patterns (and you don’t want to try something more exotic like objects that create each other with more and more information, either because performance is critical and you can’t afford it, or you dislike writing that much boilerplate to allow type-checking to verify that your object is properly created) but you otherwise want to use it, var x: X = null is what I’d choose, not _. If X is a primitive, you probably need to choose the correct value wisely anyway (for example, Double.NaN instead of 0.0, -1 rather than 0 for Int) to indicate I-am-not-initialized. If it’s generic code and you want Any instead of AnyRef, asInstanceOf-ing back and forth between Any and AnyRef is probably the best way out of poorly typechecked situation (assuming you really, really can’t use Option, which at that point is much clearer).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know there are multiple questions on here related to the same issue but
I know that there can be multiple values for an email, but I'm not
I know there are multiple questions about this same question but I couldn't find
I know there are multiple similar questions out there, but none to which were
I know there are a few questions like this but what I'm looking for
So I know there are multiple questions like this, but I think this is
I know there are multiple posts on this but I still can't get it
I know there are multiple solutions online, but some are for windows, some are
First of all, I found similar questions in SO but there is not any
I know that there has been a lot of questions like this but I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.