liveBook · Manning

Type hints

As explained in Functional Programming in Scala, Second Edition

A type annotation is syntax that explicitly specifies the type associated with a program expression or parameter.

Type hints, called type annotations, attach explicit type information to parameters, results, or function values. In Scala, a parameter such as `n: Int` declares its type, while `: Int` after a method signature declares the result type. Scala can often infer omitted types, but explicit result annotations clarify public methods. section 2.1

Type annotations support several closely related readings:

  • They document a method’s signature: `def abs(n: Int): Int` takes an integer and returns an integer. section 2.1
  • They describe function values: `(Int, Int) => Boolean` means a function taking two integers and returning a Boolean. section 2.4.2
  • They can be omitted when Scala infers function-argument types from context, as with `(x, y) => x < y`. section 2.4.2
Listing 2.1 A simple Scala program
// A comment!
/* Another comment */
/** A documentation comment */
object MyProgram:                                 #1
  def abs(n: Int): Int =                          #2
    if n < 0 then -n                              #3
    else n
 
 
  private def formatAbs(x: Int) =                 #4
    val msg = "The absolute value of %d is %d"    #5
    msg.format(x, abs(x))                         #6
 
 
  @main def printAbs: Unit =                      #7
    println(formatAbs(-42))

The listing places parameter annotations, an explicit public result annotation, and an inferred private result side by side. section 2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines parameter, result, and function-type notation, but stops short of compiler or type-inference internals.
Examples
Uses `abs`, `formatAbs`, equality lambdas, and `isSorted` to contrast explicit annotations with inferred types.
What it assumes
Assumes basic Scala method and function syntax while introducing annotation notation through small concrete programs.
What you can do after
Evaluate and write Scala signatures using parameter, result, and function-type annotations, while recognizing safe inference opportunities.
How it connects
Connects type annotations with type inference, methods, pure functions, anonymous functions, and higher-order functions.

Also explained in

Compare how 17 books explain type hints →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.