Scala contexts

We are going to formalize something we saw before but without stopping and looking at it.

Contexts are defined by{...}.

You realize that we sawcontextbefore. We saw the characters{and}in the previous SKBs.

We saw it before when we defined a method usingdef. We also saw it when we defined aclass, anobject, even aval.

If you use avalwithin a context, you are going to be using the one the closest to the context you are in. Keep in mind that it is not good practice to reuse the same name over and over as it makes the code extremely confusing and hard to debug. But this example is trying to illustrate toscopeof thevalbased on inside which context is has been declared and is being used.

Context always return a value. You can see that in the very first context defined by

1
This context is implicit, and could be re-written to:

{

1

}

This is the same concept for eachval:
val a: Int = 1
can be read as

val a: Int = {

1

}

Context always return the last line of code as its overall returned value. The other aspect to know about is related to thegarbage collectorinherited fromJava. Yes, sometimes we have to remember that Scala is based on the JVM and inherits some of its core features, one of them being thegarbage collector.

The idea behind thegarbage collectoris the memory management. Each time you create avalyou need to allocate memories to keep it “alive”. That is all well and good but if you keep creating more and more things, your computer is going to die. How do you know you can remove a value from the memory ? Context !

When the program is leaving a context, it knows it can safely remove all values that were declared in this context and free the memory.

I hope this SKB was helpful in understanding better the structure of a Scala program. As always, don't hesitate to message me or any member of our community if you need help !

Reveal more information and clues
Load Exercise