Instantiate the two type parameters and implement the function object interface:
val square: Fun[Int, Int] = new Fun[Int, Int] {
  override def apply(x: Int): Int = x * x
}
Parametric polymorphism occurs because the generic trait is specialized by choosing its argument and result types. Subtype polymorphism occurs because the anonymous implementing software class is used through a Fun[Int, Int] reference; calls to its apply operation use the object interface contract and dynamic dispatch. Multiplication itself is not the second polymorphism needed for this explanation.
For values whose mathematical squares fit in a signed 32-bit integer, the result is the ordinary square. Outside that range, the supplied integer return type cannot represent every mathematical square, and the multiplication follows Scala integer-overflow behavior. An implementation requiring exact mathematical results for all integer inputs would need a wider result type or an explicit overflow exception.
A function accepting every Base can safely be used where only Derived inputs will be supplied. The reverse direction is unsafe. A Derived argument is already a valid Base argument; restricting the possible callers introduces no new obligation for the function. This is the contravariant input rule of function subtyping.
The printed trait has generic type invariance, so Scala does not directly permit either parameter-changing assignment. The safe behavior can be exposed using an explicit adapter without changing that trait:
def restrictInput(f: Fun[Base, Base]): Fun[Derived, Base] =
  new Fun[Derived, Base] {
    def apply(x: Derived): Base = f(x)
  }
For the unsafe direction, take illustrative classes in which a derived software object has an extra operation:
class Base
class Derived extends Base { def special(): Int = 1 }
val narrow = new Fun[Derived, Base] {
  def apply(x: Derived): Base = { x.special(); x }
}
def broadClient(f: Fun[Base, Base]): Base = f(new Base)
// broadClient(narrow) must be rejected.
If that substitution were accepted, the client could pass an ordinary base software object to code that calls special, which that software object does not support. The rejected call is intentional counterexample code, not a promised compilable application. Variance annotations are needed to make sound direct conversions part of the generic trait's declared subtyping relation.[ref]
Constructing channel implementations, decorators and adapters allocates software objects that hold state and references to other software objects. As configurations and temporary processing chains are replaced, some old software objects become unreachable. A typical Scala program on a managed runtime relies on garbage collection to recycle that storage; otherwise unreclaimed allocation can exhaust the available heap memory.
A reachable wrapper keeps its wrapped component reachable. Sharing a channel among several wrappers can extend its lifetime until all relevant references disappear. Many software objects alone do not imply that collection can free them: if the program deliberately retains every channel, those software objects remain live. The reason garbage collection is useful is repeated allocation combined with changing reachability, not an assumption that the integer-returning apply operation allocates a fresh channel on every call.
The held cover identifies the Long Vacation sitting of 9 September 2021, distinct from the June paper carrying the same formal code. All eight questions and all 39 terminal leaves are answered. Scala snippets use Scala 2.13 style and the supplied interfaces. No Scala compiler is installed in the checking environment: independent models, exact calculations and Java numeric-helper checks are distinguished from native Scala or GUI execution.
Use a finite sequence as abstract state, initially empty. One Scala interface is
trait DoubleEndedQueue {
  def isEmpty: Boolean
  def addLeft(x: Int): Unit
  def getLeft(): Int
  def addRight(x: Int): Unit
  def getRight(): Int
}
The emptiness query has no precondition; its result is and its postcondition is . Adding on the left has no precondition and gives . Adding on the right gives . Both return Unit.
Each removal requires a nonempty incoming sequence. getLeft() returns its first entry and leaves the remaining final sequence; getRight() returns its last entry and leaves the remaining initial sequence. These contracts remove exactly one occurrence, so duplicate values are permitted and do not collapse the sequence into a set.
Reject the empty string because it has no positive total count to normalize:
final class DistFromString(s: String) extends FiniteDist[Char] {
  require(s.nonEmpty)
  private val frequencies =
    s.foldLeft(Map.empty[Char, Int]) { (counts, c) =>
      counts.updated(c, counts.getOrElse(c, 0) + 1)
    }

  def getDom: List[Char] = s.toList.distinct

  def getProb(c: Char): Double =
    frequencies.getOrElse(c, 0).toDouble / s.length.toDouble
}
The support contains each occurring character once, and a character absent from the string gets mass zero. The occurrence counts sum to the nonzero string length, proving normalization. For a separate example, the string "aba" gives masses and to its two characters. The interpretation follows Scala's Char elements, so it counts UTF-16 code units rather than imposing a separate Unicode-code-point representation. The Double results approximate the corresponding rational probabilities.
Choose the following explicit policy: an edit of pounds recomputes euros; an edit of euros recomputes pounds; an edit of the rate keeps pounds fixed and recomputes euros. Amounts may be any finite signed values, while a rate must be finite and strictly positive. Invalid text, non-finite numbers and overflowing conversions leave the last accepted state intact and restore its display.
import scala.swing._
import scala.swing.event.EditDone
import scala.util.Try

object CurrencyConverter extends SimpleSwingApplication {
  def top: Frame = new MainFrame {
    title = "Currency converter"
    val pounds = new TextField(8)
    val euros = new TextField(8)
    val rate = new TextField(8)
    private var poundsValue = 10.0
    private var rateValue = 1.15
    private var updating = false

    private def finite(x: Double): Boolean =
      java.lang.Double.isFinite(x)

    private def money(x: Double): String =
      java.lang.String.format(java.util.Locale.ROOT, "%.2f",
                              java.lang.Double.valueOf(x))

    private def showValues(): Unit = {
      updating = true
      try {
        pounds.text = money(poundsValue)
        euros.text = money(poundsValue * rateValue)
        rate.text = java.lang.Double.toString(rateValue)
      } finally updating = false
    }

    private def commit(field: TextField): Unit = {
      if (!updating) {
        val proposed = Try(field.text.trim.toDouble).toOption
          .filter(finite).map { value =>
            if (field eq pounds) (value, rateValue)
            else if (field eq euros) (value / rateValue, rateValue)
            else (poundsValue, value)
          }
        proposed.foreach { case (newPounds, newRate) =>
          if (finite(newPounds) && finite(newRate) && newRate > 0.0 &&
              finite(newPounds * newRate)) {
            poundsValue = newPounds
            rateValue = newRate
          }
        }
        showValues()
      }
    }

    contents = new FlowPanel {
      contents += new Label("Pounds")
      contents += pounds
      contents += new Label("Euros")
      contents += euros
      contents += new Label("Euros per pound")
      contents += rate
    }
    listenTo(pounds, euros, rate)
    reactions += {
      case EditDone(source) if source eq pounds => commit(pounds)
      case EditDone(source) if source eq euros => commit(euros)
      case EditDone(source) if source eq rate => commit(rate)
    }
    showValues()
  }
}
The numeric state has the invariant and ; euros are derived instead of being stored independently. A proposal is validated before either stored value changes. The update flag prevents a synchronous programmatic display update from recursively committing another edit. Currency amounts display two decimal places, while the rate retains its parsed precision; display rounding is not repeatedly fed back into the numeric model. Locale.ROOT ensures that formatted decimal points match the input parser.
The code handles the EditDone events used by the paper rather than trying to parse every intermediate keystroke. It uses Scala 2 style and Java 8-or-newer numeric helpers. No Scala compiler or Swing runtime execution was available in the checking environment; the state transitions were checked independently, and the API usage was compared with the supplied contract and official Scala/Swing documentation.[ref]
Worked solutions for the held Oxford preliminary examination of 14 June 2023. Source release: released examination PDF. All eight questions and all 42 answerable leaves are addressed below, without reproducing question statements. The three printed sections are retained as context within the question hierarchy.
Code uses the Scala 2 syntax of the paper. Array inputs described as sorted are assumed nondecreasing and stable during an operation. Unless explicitly discussing machine behavior, mathematical proofs state their arithmetic assumptions. In particular, the printed routines in Question 2 have genuine fixed-width arithmetic limitations, which are analyzed rather than silently attributed exact-integer behavior. Implementations below handle empty structures and document their sentinels, capacity bounds and invalid-input behavior.
Path-dependent type 2026-10-24
A type selected through a stable object path, allowing an object's nested type to retain its association with that instance. In Scala, editor.Snapshot can differ from otherEditor.Snapshot even when both objects have the same outer class. This is useful for originator-specific mementos and other values that must not be mixed across owners.[ref]
Programming language polymorphism Created 2026-10-24 Updated 2026-10-31
Using an interface or definition across multiple types. Subtype polymorphism dispatches through a common supertype; parametric polymorphism uses a type parameter uniformly; method overloading selects among signatures by static types in languages such as Scala. These mechanisms should be distinguished from genetic or materials-science polymorphism.
Relevant locators: remainder %, gcd, isValidInt and toInt. Scala's BigInt provides arbitrary-precision integer arithmetic; representability must be checked before conversion to a fixed-width integer because narrowing conversion need not preserve the exact value. The archived API corroborates the operations used in the solution without claiming a particular installed Oxford course library version.
Archived official Scala API. Relevant locators: the abstract members hasNext and next, the exhaustion exception, and the consuming nature of iterators. The associated historical overview is Collections for Scala 2.8–2.12: Iterators.
Relevant locator: Scala standard library 2.13.6: Iterator abstract members hasNext and next, exhaustion, mutation and safe reuse.
Scala Swing Created 2026-10-24 Updated 2026-11-05
Scala Swing provides Scala wrappers for Java Swing graphical user interfaces. Its notification mechanism implements an observer pattern: a publisher emits software events, and a reactor subscribes with listenTo(publisher). Adding a handler to reactions supplies a partial function that matches the software events the reactor handles. Subscription and handling are distinct: one determines which publisher is heard, and the other determines what to do with a matching notification.[ref]
For example, a button publishes a button-click notification, and a subscribed display component handles it by updating a label. Another publisher's notifications need a subscription of their own. Calling deafTo(publisher) ends the subscription to that publisher without requiring removal of every handler.[ref]
Relevant locator: Official library README, About Scala-swing: Publisher/Reactor, listenTo, reactions; archived Reactor API at www.scala-lang.org/api/2.12.7/scala-swing/scala/swing/Reactor.html corroborates listenTo, deafTo and reactions. These corroborate the supplied source contract, not a verified 2021 course dependency version.
Scala trait linearization 2026-10-31
Scala orders a class and its inherited traits to resolve member lookup and super calls. For two independent traits sharing a base, the rightmost mixed-in trait comes first, followed by the earlier trait and then the common base. Ordinary virtual calls start at the receiver's most specific override; an unqualified super call starts after the implementation's owner in that receiver's linearization. It does not necessarily call the textual parent of the trait in isolation.[ref]
Short-circuit evaluation Created 2026-10-24 Updated 2026-10-31
Evaluation that skips a later operand once an earlier operand determines the result. In Scala, p != null && p.field == x does not dereference p when it is null, and i < n && a(i) != x avoids an out-of-range access at . The order is part of the safety argument: exchanging these operands can preserve a Boolean formula in mathematics while changing whether a program raises an exception.
Singleton object 2026-10-31
A named software object instantiated once in the scope of its definition. A top-level Scala object can implement the singleton pattern. Nested object definitions can have different instances for different enclosing instances, so the relevant scope matters.
Singleton pattern 2026-10-31
Provide a shared unique instance of a service or state holder. A Scala object supplies one instance of that object definition; a top-level object can therefore centralize shared state such as a registry of current scores. A singleton does not by itself implement thread safety, remove stale entries, or define the lifetime of registered objects. Those remain separate design responsibilities.