Scala Flashcards
Methods and values that aren’t associated with individual instances of a class belong in \_\_\_\_\_\_\_ denoted by using the keyword \_\_\_\_\_ instead of class
singleton objects
object
Most singleton objects do not stand alone, but instead are associated with a class of the same name. When this happens, the singleton object is called the ______ of the class and the class is called the _______ of the object
companion object
companion class
A class and its companion object, if any, must be defined
in the same source file
static is not a keyword in Scala. Instead, all members that would be static, including classes …
should go in a singleton object.
what does => do in scala
creates an instance of a function
in scala every function is
an instance of a class
when you say 1 + 2 in Scala, you are actually
invoking a method called + defined in class int
Traits are like interfaces in Java,
but they can also have
method implementations and even fields
Functional programming is guided by two main ideas.
- A function is a value of the same status as, say, an integer or a string. You can pass functions as arguments to other functions, return them as results from functions
- Operations of a program should map input values to output values rather than change data in place (data structures are immutable)
How would you write this in scala? // this is Java boolean nameHasUpperCase = false; for (int i = 0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { nameHasUpperCase = true; break; } }
val nameHasUpperCase = name.exists(_.isUpper)
The predicate _.isUpper is an example
of a function literal
A function literal can be called a predicate if
its result type is Boolean
What does a static type system do?
classifies variables and expressions according to the
kinds of values they hold and compute
val msg = “Hello, world!”
neither java.lang.String nor String appear anywhere
in the val definition. Why?
this is an example of type inference
the first element in a Scala array
named steps is
steps(0) not steps[0] as in java
what is the syntax for a function literal
a list of named parameters, in parentheses, a right arrow, and then the body of the function.
(x: Int, y: Int) => x + y
when you type 1 + 2
into the Scala interpreter what are you actually doing
invoking a method
named + on the Int object 1, passing in 2 as a parameter
Scala’s List, scala.List, differs from Java’s java.util.List
type in that Scala Lists are …
always immutable
What is the method on Scala’s List that is used for concatenation
:::
What is :: in Scala
“Cons” it prepends a value to the beginning of a list
If a method is used in operator notation, such as a * b, the
method is invoked on the left operand, as in a.*(b)—unless …
the method name ends in a colon. If the method name ends in a colon, the method is
invoked on the right operand. Therefore, in 1 :: twoThree, the :: method
is invoked on twoThree
What is the append operation for a list?
:+
What does this do?
val thrill = “Will” :: “fill” ::
“until” :: Nil
Creates a new List[String] with the
three values “Will”, “fill”, and
“until”
val oneTwoThree = 1 :: 2 :: 3 :: Nil
why is there a Nil at the end?
The reason you need Nil at the end is that :: is defined on class List. If you try to just say 1 :: 2 :: 3, it won’t compile because 3 is an Int, which doesn’t have a :: method
what does
List(“a”, “b”) ::: List(“c”, “d”) do
concatenates the two lists into a single list
thrill.count(s => s.length == 4)
what does this do?
Counts the number of string elements in
thrill that have length 4
thrill.drop(2)
assuming thrill is a list what does this code do
returns the list without the first two entries
thrill.dropRight(2)
assuming thrill is a list what does this code do
Returns the thrill list without its
rightmost 2 elements
thrill.exists(s => s == “until”)
assuming thrill is a list what does this code do
Determines whether a string element
exists in thrill that has the value
“until”
assuming the list was called thrill how would you return a list of all elements, in order, of
the thrill list that have length 4
thrill.filter(s => s.length ==4)
Indicates whether all elements in the
thrill list end with the letter “l”
thrill.forall(s=>s.endsWith(“l”))
Returns the first element in the thrill
list
thrill.head
Returns a list of all but the last element in
the thrill list
thrill.init
Indicates whether the thrill list is
empty
thrill.isEmpty
Returns a list resulting from adding a “y”
to each string element in the thrill list
thrill.map(s=>s + “y”)
Another useful container object is the tuple. Like lists, tuples are immutable,
but unlike lists, tuples can
contain different types of elements
Whereas in Java you would often create a JavaBean-like class to hold the multiple return values, in Scala you can simply return a
Tuple
to instantiate a new tuple that contains some objects simply
place the objects in parentheses, separated
by commas.
why you can’t access the elements of a tuple
like the elements of a list, for example, with “pair(0)”.
The reason is that a list’s apply method always returns the same type (as a method always should) but each element of a tuple may be a different type.
Because Scala aims to help you take advantage of both functional and imperative styles, its collections libraries make a point to differentiate between mutable and immutable collections. For example
lists are always immutable
arrays are always mutable
are Sets and Maps mutable or immutable in Scala?
Scala supports mutable and immutable sets and maps though the default is immutable
If the default Set declaration myset = Set(“blah”,”blah”) creates an immutable set how do you create an immutable one
You need to import the library
import scala.collection.mutable.Set
first
The telltale sign of a function with
side effects is that its result type is
Unit
If the function is not returning anything interesting then it must be producing a side effect
val lines = Source.fromFile(args(0)).getLines().toList
why do you need the toList
The final toList is required because the getLines method returns an iterator.
Once you’ve iterated through an iterator, it is spent. By transforming it
into a list via the toList call, you gain the ability to iterate as many times
as you wish
what does the reduceLeft method do?
works by applying the function/operation you give it, and applying it to successive elements in the collection. The result of the first comparison is used in the second comparison, and so on.
how do you declare a method in scala
def
how do you make members public in scala
you don’t do anything explicitly
members are public by default
One im- portant characteristic of method parameters in Scala is that
they are vals not vars
One puzzler to watch out for is that whenever you leave off the equals sign before the body of a function, its result type will definitely be
Unit
what is returned by this def g() { "blah" } why?
Unit
there is no ‘=’ before the body of the function
one way in which Scala is more object-oriented than Java is
Scala cannot have static members, it uses singleton objects
When a singleton object shares the same name with a class, it is called that class’s
companion object
A class and its companion object can access …
each others private members
can singleton objects take parameters?
Why?/Why not?
No
You cannot instantiate an object using new - thus there is no way to pass parameters
To run a Scala program, you must
Supply the name of a standalone singleton object with a main method that takes one parameter, an Array[String],
What can you do instead of creating a singleton object with a main method?
write “extends Application” after the name of your singleton object
Inheriting from Application is shorter than writing an explicit main method, but it also has some shortcomings.
- you can’t use this trait if you need to access command-line arguments,
- you need an explicit main method if your program is multi-threaded.
- some implementations of the JVM do not optimize the initialization code of an object which is executed by the Application trait. So you should in- herit from Application only when your program is relatively simple and single-threaded.
In Scala operators are not special language syntax - what does this mean
any method can be an operator
what is infix operator notation?
method to invoke sits between the object and the parameter or parameters you wish to pass to the method, as in “7 + 2”
what is prefix operator notation
method to invoke sits before the object e.g. -7
In Scala, you can leave off empty parentheses on method calls. The convention is that you include parentheses if …
the method has side effects, such as println()
How many parameters does a postfix operator take?
What does this mean for notation?
postfix operators take no parameters
no brackets
In Java, classes have constructors, which can take parameters, whereas in Scala,
classes can take parameters directly
The syntax of a for-yield expression is like this
for yield
scala’s ____ expression allows you to select from a number of alternatives, just like switch statements in other languages
match
(x: Int) => x + 1
what does => designate
designates that this function converts the thing on the left (any int) to the thing on the right (x+1)
you can use underscores as placeholders for one or more parameters, so long as
each parameter appears only one time within the function literal.
The function literal _ > 0, therefore, is equivalent to the slightly more verbose
x => x > 0
A partially applied function is an expression in which
you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.
what is going on here
val partialSum2ArgumentsProvided = sum(1, 2, _:Int)
this is a partially applied function, what is returned is not a value but a function with two of its arguments pre-supplied
(x: Int) => x + 1 why is this not a closure in the strictest sense?
Because it is already closed there are no free variables
any function value created at runtime from (x: Int) => x + more will by definition require that a binding for its free variable “more” be
captured. The resulting function value, which will contain a reference to the captured “more” variable, is called a
closure
def plainOldSum(x: Int, y: Int) = x + y write this as a curried function
def curriedSum(x: Int)(y: Int) = x + y
how would you invoke def curriedSum(x: Int)(y: Int) = x + y
curriedSum(1)(2)
curriedSum(x: Int)(y: Int) = x + y
how would you get an actual reference to curriedSum’s “second” function
val onePlus = curriedSum(1)_
is a placeholder for the second parameter list
what is happening here
val someValue = foobar(1)_
someValue is a reference to the second part of a partially applied curried function.
When invoked, adds one to its sole Int argument and returns the result
loan pattern
a control-abstraction function opens a resource and “loans” it to a function and cleans up when the function is finished
what are composing operators often called
combinators
Thinking in terms of combinators is generally a good way to approach library design - why
it pays to think about the fundamental ways to construct ob- jects in an application domain.
A class with abstract members must
itself be declared as abstract
how do you make a scala class abstract
by writing an abstract modifier in front of the class keyword: abstract class Element