Lecture - Imperative Programming TT23, III
- Overriding vs overloading
- Overriding means the method has the same name and type, and the one to run depends on the dynamic type of an object. This is resolved at runtime.
- Overloading uses different implementations depending on the types of the parameters. This is resolved at compile time using type inferences.
- the Any class
- Every class in Scala is a subclass of the Any class
- Encapsulation
- Big reason for why it’s useful: hiding things that could violate the representational invariant
- But it can be an issue when the class doesn’t provide all the operations a user needs
The iterator pattern
trait Iterator[+T] {
def hasNext() : Boolean
def next() : T
}
-
+T
since Iterator is a covariant type, i.e. ifPlaneText <: Text
, thenIterator[PlaneText] <: Iterator[Text]
.
Flashcards (GPT-4)
What is the difference between overriding and overloading in methods?
Overriding: same method name and type, resolved at runtime; Overloading: different implementations based on parameter types, resolved at compile time.
What is the Any class in Scala?
The Any class is the superclass of all classes in Scala.
Why is encapsulation useful and what is a potential issue?
Useful for hiding things that could violate representational invariants; Issue: may not provide all needed operations for users.
What is the iterator pattern in Scala? Provide a basic example.
A design pattern for traversing elements in a collection, e.g., trait Iterator[+T] { def hasNext(): Boolean; def next(): T }
.
What does the covariant type notation +T
mean in Scala?
+T
mean in Scala?+T
indicates a covariant type, meaning if A <: B
, then C[A] <: C[B]
for some generic class C
.