Scope doesn’t creep; understanding grows
“Scope doesn’t creep; understanding grows.”
From Jeff Patton in User Story Mapping (something I tried to explain to people many years ago)
“Scope doesn’t creep; understanding grows.”
From Jeff Patton in User Story Mapping (something I tried to explain to people many years ago)
If you add ScalaCheck to an SBT project like this:
libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.13.4" % "test"
it’s only available in the SBT “test” scope. This means that when you start a Scala REPL session inside of SBT with its console
command, the ScalaCheck library won’t be available in that scope.
To use ScalaCheck with the SBT console (REPL), don’t use its console
command — use test:console
instead. A complete example looks like this:
$ sbt > test:console scala> import org.scalacheck.Gen.choose
Note that after you type test:console
your project may be compiled, so that step may take a few moments.
In summary, use SBT’s console
command to start a “normal” Scala REPL inside SBT, and use test:console
to start a REPL that you can run tests inside of. (Note that this same advice also applies to using ScalaTest or specs2.)
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 9.5, “How to use closures in Scala (closure examples, syntax).”
Back to topYou want to pass a function around like a variable, and while doing so, you want that function to be able to refer to one or more fields that were in the same scope as the function when it was declared.
Back to topYou can demonstrate a closure in Scala with the following simple (but complete) example:
Back to topThis is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 7.6, “How to use import statements anywhere (methods, blocks) in Scala.”
You want to use an import
statement anywhere, generally to limit the scope of the import, to make the code more clear, or to organize your code.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 5.1, “How to control method scope in Scala (private, package, more).”
Back to topScala methods are public by default, and you want to control their scope in ways similar to Java.
Back to topScala lets you control method visibility in a more granular and powerful way than Java. In order from “most restrictive” to “most open,” Scala provides these scope options:
Back to topPerl function FAQ: How do I make variables private to my Perl function?
Answer: Just use the Perl my
operator. Here's an example that shows how to create a variable named bar
that is private to the function name foo
: