scope

How to use ScalaCheck in the SBT console

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.)

How to use closures in Scala (closure examples, syntax) alvin June 14, 2015 - 6:54pm

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 top

Problem

You 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 top

Solution

You can demonstrate a closure in Scala with the following simple (but complete) example:

Table of Contents

  1. Problem
  2. Solution
Back to top

How to use import statements anywhere (methods, blocks) in Scala

This 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.”

Problem

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.

How to control Scala method scope with private, package, and more

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 top

Problem

Scala methods are public by default, and you want to control their scope in ways similar to Java.

Back to top

Solution

Scala 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:

Table of Contents

  1. Problem
  2. Solution
Back to top

How do I make variables private to my Perl function?

Perl 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: