-1

Can anybody please help me with this exercise, I have gone through it a million times and I cannot understand how the output can be 42. I especially struggle with val bp. A walkthrough the code would be highly appreciated. Thanks a lot!

 object Scope {
    var a : Int = 1
    var b : Int = 3
    var c : Int = 0
  
    def m1(b : Int) : Int = {
       a = 5
       c += a + b
       b + 3
    }
    
    def m2(a : Int, d : Int) : Int = {
       b = c
       val bp = m1(a - d)
       c += b + bp
       b + c
    }

    def main(args : Array[String]) : Unit = {
       b = m1(a)
       a = m2(b,a)
       c += a
       println(c)
    }
} 
3
  • 7
    You can consider this exercise as a good opportunity to master your skill of using debugger. Commented Oct 10, 2022 at 16:51
  • 11
    Doesn't appear like this exercise is worth "exercising". It is just some non-idiomatic, very badly written code, that is intentionally made obscure. Just throw it out. In real life, you are not likely to need to use vars and mutable state, extremely unlikely to encounter actually useful code that is written to shadow class member names with method parameters, and also rather unlikely to often have to deal with single-letter variable names, or methods named like m1 or m2. Do yourself a favor and throw out whatever book you found this exercise in, it's not teaching you anything useful. Commented Oct 10, 2022 at 17:02
  • 5
    This example does a lot of variable overshading. Open it in IDE, place your cursor at input parameter and use rename functionality. You'll find that m1's b parameter is not var b, m2's a is not var a and so on. As @DmytroMitin said use debugger - it will show you how variables are initalized and modified step by step. Commented Oct 10, 2022 at 17:55

1 Answer 1

3

To summarise the comments, this is a really poor piece of code and nobody would write real Scala code like this. Abandon whatever course it is that is using this exercise and find a functional course of some kind (e.g. this course by the person who invented the language)

If you really want to understand this code, it will be much easier with a tool like IntelliJ IDEA which has great Scala support. Start by renaming the function parameters a and b so there are no duplicate names to confuse things. Then use the debugger in IntelliJ IDEA to step through the code and see how each value changes as it is executed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.