Functions

Introduction to Scala

David Venturi

Curriculum Manager, DataCamp

Twenty-One

Twenty-One card values

1 http://bit.ly/twenty_one_wikipedia
Introduction to Scala

Functions

In this course

  • Understand what functions are
  • Call a function
Introduction to Scala

What is a function?

What do functions do?

  • Functions are invoked with a list of arguments to produce a result

What are the parts of a function?

  1. Parameter list
  2. Body
  3. Result type
Introduction to Scala

What is a function?

What do functions do?

  • Functions are invoked with a list of arguments to produce a result

What are the parts of a function?

  1. Parameter list
  2. Body
  3. Result type
Introduction to Scala

A specific question

King and a ten

scala> 20 > 21
false
Introduction to Scala

Generalizing that question

Two cards with question marks inside

Introduction to Scala

Generalizing that question

Three cards with question marks inside

Introduction to Scala

Generalizing that question

Two cards with question marks inside

scala> 20 > 21
Introduction to Scala

Generalizing that question

Two cards with question marks inside

scala> hand > 21
Introduction to Scala

The bust function

Two cards with question marks inside

// Define a function to determine if hand busts
def bust(hand: Int): Boolean = {
  hand > 21
}
  • Function body: follows equals sign = in curly braces {}
Introduction to Scala

The bust function

Two cards with question marks inside

// Define a function to determine if hand busts
def bust(hand: Int) = {
  hand > 21
}
  • Function body: follows equals sign = in curly braces {}
Introduction to Scala

What do functions do again?

  • Functions are invoked with a list of arguments to produce a result
  • Functions are first-class values
// Define a function to determine if hand busts
def bust(hand: Int) = {
  hand > 21
}

println(bust(20)) println(bust(22))
false
true
Introduction to Scala

Call a function with variables

King and a ten

println(bust(kingSpades + tenHearts))
false
Introduction to Scala

Let's practice!

Introduction to Scala

Preparing Video For Download...