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
A method is abstract if
it does not have an implementation (i.e., no equals sign or body).
uniform access principle
client code should not be affected by a decision to implement an attribute as a field or method
what is an empty-paren method
methods defined with empty parentheses, such as def height(): Int
when can you use an parameterless method rather than an empty-paren
when your method only reads local val’s and does not change mutable state
Can you override a parameterless method with an empty-paren method, and vice versa
yes
To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as
parameterless methods
Inheritance means that all members of the superclass are also members of the subclass, with two exceptions.
- Private members of the superclass are not inherited
2. It is not inherited if a class with the same name and signature is already in the subclass (it is overridden)
what does subtyping mean
a value of the subclass can be used wherever a value of the superclass is required.
Scala, fields and methods belong to the same namespace. This makes it possible for
a field to override a parameterless method
Generally, Scala has just two namespaces for definitions in place of Java’s four. Java’s four namespaces are fields, methods, types, and packages. By contrast, Scala’s two namespaces are:
- values (fields, methods, packages, and singleton objects)
* types (class and trait names)
Difference in memory utilization in threaded and evented web servers
Evented web servers make much better use of hardware resources than threaded ones.
In scala you must use _____ not ______ to convert between numeric types for example to convert 99.44 to an integer use
methods
casts
99.44.toInt
a + b is shorthand for
a.+(b)
in a.+(b) which is the method
+
in general ______ is shorthand for a.method(b)
a method b
from a style point of view when should you not use parenthesis
when there are no parameters and the method has no side effects
to find the fourth element of a string you would use ____
not _____ as in other languages
mystring(4)
mystring[4]
Occasionally the () notation conflicts with another scala feature namely
implicit parameters.
Why would “Bonjour”.sorted(3) yield an error? What would be a solution
because the sorted method can optionally be called with an ordering (implicit parameter)
To solve this call the apply method explicitly as in “Bonjour”.sorted.apply(3)
A method to determine how many uppercase letters are in a string “ThisString”
“ThisString”.count(_.isUpper)
In scala what are square brackets used for
for Type parameters
how would you determine whether the string “big bloody wombat” contained the word bloody?
“big bloody wombat”.constainsSlice(“bloody”)
What is the value of a block in scala
the value of its last expression
What is the void type in scala
Unit
Why is
val s = if (x > 0) 1 else -1
better than
if (x >0) s=1 else s=-1
The first form is better because s is a val not a var
A block that ends with an assignment such as
{r = r * n; n-= 1} has a value of
Unit
(Assignments have a Unit Value) the last statement in the block is an assignment
since assignments have Unit value what should we not do
chain them together
x = y = 1
what are the three string interpolators in the Scala library?
f, s and raw
What is the difference between the string interpolators f, s and raw
f - contains expressions that prefixed with a $ and are optionally followed by a C style format string
s- contains expressions but not format directives
raw - escape sequences are ignored.
How do you include a $ sign in an interpolated string
double it $$
if you want a dollar sign to appear before the value of price $$$price
for (i
makes the variable i traverse all the values of the expression to the right
how do you define a function
specify the functions name, parameters and body def abs(x: Double) = if (x >= 0) x else -x
is a return type necessary in scala
only when the function is recursive
Why would you not use a return function?
return is a kind of break statement that ends the execution of a function. While this is okay in a named function it is a problem in anonymous functions, because it would break out of any enclosing named function
implement a function called sum that takes a variable number of arguments
def sum(args: Int*) { blah }
What is the difference between a function and a procedure in the way that they are declared?
When a function body is enclosed in braces without a preceeding = symbol it returns a Unit and it is called a procedure
declare a val whose initialisation is deferred until accessed for the first time
lazy val words = scala.io.Source.fromFile(“/usr/share/dict/words”).mkstring
What are checked exceptions and how are they used in scala
In java checked exceptions are checked at compile time. If your method might throw an IOException you must declare it - in the method signature Scala does not use checked exceptions.
Use an ______ if the length is fixed and an _______ _____ if the length can vary
Array
Array Buffer
how do you travers an the elements of an array
(elem
Java has ArrayList and C++ has vector for arrays that grow and shrink on demand what is the scala equivalent?
ArrayBuffer
you can append any collection with …
++=
how would you remove the last five elements of an array
arrayname.trimEnd(5)
How would you add Array(1,2,3,4) to your existing array called stuff
stuff ++= Array(1,2,3,4)
how do you add to an array at a specific location
insert(,)
how would you convert an array to an array buffer
a.toBuffer
how would you display the contents of an array with a “and” between each item
myArray.mkString(“ and “)
To create a multidimensional array use the ____
ofDim method of the Array class
What is another word for a map
a hash table
maps are collections of
key value pairs
what is a tuple
a collection of n objects not necessarily of the same type
in a quiz alice scored 3 dave scored 5 and rod scored 12
how would you create an immutable map called scores containing these values
val scores = Map(“alice” -> 3, “dave” -> 5, “rod” -> 12)
what does the -> operator do
makes a pair
A tuple value is formed by
enclosing individual values in parenthesis
If you have a tuple
val t = ( 1, 3.14, “Fred”) you can access its components with the methods
_1, _2, and _3
unlike array or string positions the component positions of a tuple start with
1 not 0
One reason for using tuples is to bundle together values so that they can be processed together this is commonly done with the ____ method
zip
how would you create a pairs array that links the arrays symbols and counts together so that each element of symbols is paired with each element of counts
val pairs = symbols.zip(counts)
what is age_=
an automatically generated setter method for the age propery
what does the private [classname] qualifier for a field do
states that only methods of the given class can access the given field.
scala has one constructor that is more important than all the others called the
primary constructor
auxiliary constructors are called
this
each auxiliary constructor must start with a call to
a previously defined auxiliary constructor or the primary constructor
a class for which you not define a primary constructor has a
primary constructor with no arguments
explain this code def this(name: string) { this() this.name = name }
It is an auxiliary constructor
it is called ‘this’ and the first thing it does is call the primary constructor this()
What happens if a primary constructor is private
A user must then use an auxiliary constructor to construct the object
scala has not static methods or fields instead you use
the object construct
When is the constructor of an object called
when the object is first executed, if an object is never used its constructor is not executed
An object can have all the features of other class it can even extend classes or traits. There is just one exception
You cannot provide constructor parameters
When would you use an object in scala
- As a home for utility functions or constraints
- When a single immutable instance can be shared efficiently
- when a singleton is required
In Java and C++ you can have a class with instance methods and static methods. In Scala you achieve this by
having a class and a companion object
Where must a companion object be located
In the same file source file as the class. In the REPL you must use :paste
It is common for all objects to have an apply method. The apply method is called for expressions of the form
object(arg1 … argN)
It is easy to confuse Array(100) and new Array(100) what is the difference
The first expression calls apply(100), yielding an Array[Int} with the single element the integer 100. The second expression invokes the constructor this(100). The result is an Array[Nothing] with 100 null elements
Each Scala program must start with …
on objects main method of type Array[String] => Unit
If you were to create a method called blowme of type Array[String] => Unit what would it look like
def blowme(args: Array[String]) { println("I don't return anything") }
In scala you must use the _____ modifier when you override a method that is not abstract
override
To test whether an object belongs to a given class use
isInstanceOf[TypeName] method
If you want to test whether p references an Employee object but not a subclass use
if (p.getClass == classof[Employee])
A scala class can extend a Java class. Its primary constructor must invoke
one of the constructors of the Java superclass
As in Java you can use the abstract keyword to denote a class that
cannot be instantiated - usually because one or more of its methods are not defined
In Scala unlike Java you do not use the abstract keyword for an abstract method you simply
omit its body
In a subclass you need not use the override keyword when you
define a method that was abstract in the superclass
To convert a string to a number use the
toInt or toDouble method
how would you read from a text file in scala
import scala.io.Source
val source = Source.fromFile(“myfile.txt”)
val lineIterator = source.getLines
val thing = source.getLines
What can you do with the result
It is an iterator you can use it as follows
for(j
what should you do to when you are finished using the source object
call close
to read individual characters from a file you can use
the source object directly as in
for (c
Associative maps are very useful because they help keep programs legible and concise. However, sometimes you might not agree with their “one size fits all” philosophy, because you need to control the properties of the maps you use in your program in a more fine-grained way. Scala gives you this fine-grained control if you need it, because
maps in Scala are not lan- guage syntax. They are library abstractions that you can extend and adapt.
What are actors
concurrency abstractions that can be implemented on top of threads
An actor can perform two basic operations
message send and receive
The send operation is denoted by
!
Every actor has a mailbox in which
incoming messages are queued
An actor handles messages that have arrived in its mailbox via a
receive block
what problem with multiple inheritance does the traits system avoid
“diamond inheritance” problems which arise when the same class is inherited via several different paths.
What do we mean when we say functions are first class values
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, or store them in variables.
- You can also define a function inside another function, just as you can define an integer value inside a function.
- You can define functions without giving them a name - function literals
Functional programming is guided by two main ideas.
- Functions are first-class values.
- A program should map input values to output values rather than trying to change data in place
(no side effects)
args.foreach(arg => println(arg))
what would also work? Why?
args.foreach(println)
If a function literal consists of one statement that takes a single argument, you need not explicitly
name and specify the argument.
When you declare an array with val how is it still mutable?
The array itself cannot change (still the same length and type) but the elements inside the array can.
For an immutable sequence of objects that share the same type you can use
Scala’s list class
Scala’s List, scala.List, differs from Java’s java.util.List type in that
Scala Lists are always immutable (whereas Java Lists can be mutable).
Perhaps the most common operator you’ll use with lists is ‘::’, which is pronounced …
cons
Higher order functions
These are functions that take a function as a parameter or return function
Call by value:
Call by value: evaluates the function arguments before calling the function
evaluates the function arguments before calling the function
Call by value:
Call by name:
Call by name: evaluates the function first, and then evaluates the arguments if need be
evaluates the function first, and then evaluates the arguments if need be
Call by name:
def example = 2 //when is this evaluated?
when called
val example = 2 // when is this evaluated
immediately
lazy val example = 2 //when is this evaluated
when needed
def square(x: Double) //call by value or name
value
def square(x: => Double) //call by value or name
name
how do you ensure that the arguments in a class constructor have meet certain requirements?
use the require function
require(y > 0, “y must be positive”)
In Scala, the standard is to indent using ? spaces (no tabs).
2
The substitution model (lamda calculus) can only be applied to expressions that
do not have a side effect
What is the advantage of call by value
It evaluates every function only once
Both call by value and call by name evaluation strategies reduce an expression to the same value provided …
both evaluations terminate
If the call by value (CBV) evaluation of an expression terminates then … but …
The call by name (CBN) evaluation of that expression will also terminate - but the same is not true the other way round
What is the default method of evaluation for scala
Call by value
How would you force a call by name?
You would insert => between the name of the value and the type myVal: => Int
Work out the rewrite rules for booleans for
if(b) e1 else e2
if(true) e1, else e2 -> e1
if(false) e1, else e2 -> e2
def loop: Boolean = loop def x = loop would this work? Why / Why Not?
Yes, because def x = loop evaluates only when it is executed (by name) so it would not try to execute the infinite loop