T or F. def foobar = expression cannot be re-assigned.
True
What is the advantage of lambdas?
Unlike regular functions then act like variables:
- we can reassign them
Define HoF.
A higher-order function is a function that accepts as argument, or returns another function.
Why not use for each loop?
It returns unit so in order to do anything its lambda argument must be impure (have side effects). This is not good practice in FP.
What are the disadvantages for the traditional loop approach?
Define map.
Applies a given lambda to each element of a collection to return a transformed collection of the same type. Elements in transformed collection don’t have to be same type.
Define filter.
Selects elements of original collection for which given predicate is True.
T or F. All HoFs create a new collection. They do not alter the original.
True
Define reduce.
Combines the elements of collection (of type T) into a single value of type T.
Define fold.
Works like reduce. But has initial seed value and can reduce to different type.
Define flatten.
Flattens nested collections into a single collection. All elements must be collections.
What does the term first-class values mean?
Means it (e.g. function, object) can be treated like any other value. Passed as argument, assigned to variables, stored in collections and returned from functions.
class Person:
private var age = 0
def compare(other: Person) =
age > other.age
Is the access to other.age legal? Why?
Yes. Privacy is class-based.
Define method signature.
A method’s name and the number and type of its arguments.
What is method overloading? Who decides which method to use?
Having multiple methods with the same name within a class but with different arguments.
Compiler.
What is an object? What is its type?
A single instance that can be accessed through the objects name. They are usually globally accessible.
Singleton.
What is a Singleton?
Structure with a single instance shared among entire program.
What is companion object and companion class?
Companion object has the same name as companion class. Each instance of companion class shares a single instance of companion object. Works like static in Java. Also, they can access each others private fields.
T or F. A function is just an object with an apply method.
True
What is a factory method?
Constructor proxy in the companion object made by defining apply method within the object.
What is the difference between the effect of new Array(100) and Array(100)?
The latter invokes the apply method.
When we create a normal class, what is generated also?
A companion object with a default apply method.
val numbers = Array(1,2,3)
println(numbers(1))
What is happening here in terms of function calls?
1st line calls apply method in Array companion object.
2nd line calls apply method in Array class.