Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exercise 4.3.5 Scope: questionable "circular dependency" #62

Open
eed3si9n opened this issue Jan 21, 2019 · 0 comments
Open

Exercise 4.3.5 Scope: questionable "circular dependency" #62

eed3si9n opened this issue Jan 21, 2019 · 0 comments

Comments

@eed3si9n
Copy link

https://github.com/underscoreio/creative-scala/blob/develop/src/pages/programs/names.md#exercises--

original

object One {
  val a = b - 1
  val b = a + 1

  val answer = a + b
}

Trick question! This code doesn't work. Here a and b are defined in terms of each other which leads to a circular dependency that can't be resolved.

problem

I think the reason because this code doesn't work is actually two folds.

  1. Circular declaration itself is not forbidden with Scala. It just requires a type annotation on b as val b: Int = a + 1.
  2. The reason it doesn't "work", as in it will actually return incorrect value is because val a = b - 1 is referencing b before it is initialized, which seems to be treated as 0. Making answer into (0 - 1) + (0 - 1 + 1), which is -1.
scala> object One {
     |   val a = b - 1
     |   val b: Int = a + 1
     |
     |   val answer = a + b
     | }
<console>:12: warning: Reference to uninitialized value b
         val a = b - 1
                 ^
defined object One

scala> One.answer
res1: Int = -1

expectation

If we want to expose the readers to val initialization order issue, it might be worth changing the exercise to:

object One {
  val a = b - 1
  val b = 10

  val answer = a + b
}

and note that fact that without -Xfatal-warnings one could end up with incorrect answer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant