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 saw context before. We saw the characters { and } in the previous SKBs.

We saw it before when we defined a method using def. We also saw it when we defined a class, an object, even a val.

If you use a val within 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 to scope of the val based 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 each val:
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 the garbage collector inherited from Java. Yes, sometimes we have to remember that Scala is based on the JVM and inherits some of its core features, one of them being the garbage collector.

The idea behind the garbage collector is the memory management. Each time you create a val you 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