Skip to the page
The language / Methods

Start here01

The language02

Programs and the world03

Kiln04

02 The language / 11

Methods

Defining, returning, calling, default values, and what a method can see.

A method gives a piece of work a name. It takes what it needs as typed parameters, says what it gives back, and sees nothing of the script around it, so its signature tells you everything it depends on.

Here are two. total gives back a Float, worked out with the static TAX_RATE; greet gives nothing back and only prints:

total-and-greet.hem
static TAX_RATE = 0.25

def total(price: Float, quantity: Int): Float
  const subtotal = price * quantity

  return subtotal * (1 + TAX_RATE)
end

def greet(name: String)
  print("Hi, #{name}!")
end

print(total(10.0, quantity: 3)) # prints 37.5
greet("Ada")                    # prints Hi, Ada!

Methods inside a class work the same way, with a few more rules: see Classes. A method can also take a block, covered in Blocks.

Defining

A definition is def, the name, the parameters in parentheses (no space before (), then optionally : ReturnType. The body follows on the next lines, and end closes it. A method without parameters still has parentheses: def answer(): Int.

Every parameter needs a type: name: Type. A type may be optional (String?) to accept nil.

def is only allowed at the top level of a file, not inside if, while or another def. Methods can be defined anywhere in the file and called from anywhere, even before their def. Two methods can't share a name, and a variable can't have a method's name.

Returning

With a return type, the method gives a value with return value, and it must return on every path, so no call can end without one. Ending with an if counts only if it has an else and every branch returns:

return-on-every-path.hem
def sign(n: Int): Int
  if n > 0
    return 1
  else if n < 0
    return -1
  else
    return 0
  end
end

A when whose is lines all end with return counts too, since it handles every value.

Without a return type, the method gives nil. A bare return leaves early; return value is an error. Code directly after a return can never run, so it is an error. The returned value must match the return type:

wrong-return-type.hem
def half(n: Int): Int
  if n == 0
    return 0.0 # error: half must return an Int, but returned a Float
  end

  return (n / 2).floor() # floor gives an Int
end

Calling

Call with parentheses, with no space before (: total(10.0, quantity: 3). Only the first argument goes without a name; the others are written with their parameter's name, as Named arguments explains. A method without parameters is called with empty parentheses: answer(). Its name alone, answer, is a mistake that says so.

Every parameter without a default needs an argument, and each argument must match its parameter's type:

argument-types.hem
def double(n: Int): Int
  return n * 2
end

print(double(2))   # prints 4
print(double(2.5)) # error: argument 'n' of double must be an Int, got a Float

Default values

A parameter may have a default value. Its argument can then be left out:

default-values.hem
static GREETING = "Hi"

def greet(name: String, greeting: String = GREETING, times: Int = 1)
  var i = 0

  while i < times
    print("#{greeting}, #{name}!")

    i = i + 1
  end
end

greet("Ada")                    # prints Hi, Ada!
greet("Ada", greeting: "Hello") # prints Hello, Ada!

Any parameter may have a default, the first too. When the first is left out, the call starts with a named argument: greet(greeting: "Hello").

A default can only use values, statics and methods, not other parameters. It's worked out each time the method is called without that argument.

What a method can see

A method works only with what it's given and what's fixed for the whole file. That way, everything a method depends on is visible in its signature or is static. It can see:

  • Its parameters, which are constants.
  • Its own variables, which disappear when it returns.
  • Statics and all methods.

Since parameters are constants, change a copy instead:

parameters-are-constants.hem
def grow(amount: Int): Int
  var bigger = amount # amount itself can't change

  bigger = bigger + 1

  return bigger
end

A method never sees a var or const of the file's script. Anything it needs from there must be passed in:

no-script-variables.hem
var count = 0
const limit = 10

def bump()
  count = count + 1 # error: 'count' is a var of the file's script; a method can only use its parameters, its own variables, statics and other methods

  print(limit) # error: 'limit' is a const of the file's script; a method can only use its parameters, its own variables, statics and other methods
end

Statics are set up in order, before the script runs. A static whose value calls a method that uses a later static is a mistake, where the call is: 'RATE' is used before it's set up. Put statics that others use first. (A method called on an object other than self is followed only when the program runs, and stops it there.)

Recursion

Methods may call themselves. At most 10,000 calls can be in progress at once; past that, the program stops with an error instead of crashing:

message
error: too many nested method calls (more than 10000); check for recursion that never stops

Methods as values

A method's type is written with the types it takes in parentheses, then what it gives: (Int): Int, (String) for one that gives nothing, (Int): Int! for one that can fail. A parameter, a variable or a field of that type holds a method: pass the method by its name, without parentheses, and call it from there.

methods-as-values.hem
def double(n: Int): Int
  return n * 2
end

def twice(change: (Int): Int, n: Int): Int
  return change(change(n))
end

print(twice(double, n: 5)) # prints 20

A field holds one the same way, and object.field(...) calls it:

held-in-a-field.hem
class Way
  readable const path: String
  readable const to: (String): String
end

def hello(name: String): String
  return "hello #{name}"
end

const way = new Way(path: "/", to: hello)

print(way.to("you")) # prints hello you
  • A held method takes its arguments in order, unnamed: change(1).
  • One that can fail is passed on with try, or handled with rescue, as any call that can fail is.
  • The method must be of exactly that type: one that can fail doesn't go where one that can't is wanted.
  • A method's name without parentheses is a value only where a method type is wanted: const kept: (Int): Int = double holds it, and const kept = double is an error.

Generics

A generic is a class, a record or a method written once for any types, and still checked: its type parameters, in brackets after its name, stand for the types it's used with.

generic-pair.hem
record Pair[First, Second]
  first: First
  second: Second
end

def swapped[First, Second](pair: Pair[First, Second]): Pair[Second, First]
  return new Pair(first: pair.second, second: pair.first)
end

const pair = new Pair(first: 1, second: "one") # a Pair[Int, String]

print(swapped(pair).first)  # prints one
print(swapped(pair).second) # prints 1
  • A type parameter is named like a type, for what it stands for (Item, Row, Key), never a single letter.
  • The types come from the arguments: new Pair(first: 1, second: "one") is a Pair[Int, String]. Where nothing shows them, they're written after the name, empty[String]() or new Stack[Int](), and only there: written where the arguments show them, they're an error.
  • A generic type is written with its types, Pair[Int, String], wherever a type goes.
  • A generic is checked once, where it's written: a mistake in it is reported there, and a use with the wrong types where it's used.
generic-stack.hem
class Stack[Item]
  readable var items: [Item] = []

  def push(item: Item)
    self.items.push(item)
  end
end

def empty[Item](): [Item]
  const none: [Item] = []
  return none
end

var words = new Stack[String]()

words.push("hello")
print(words.items)            # prints ["hello"]
print(empty[Int]().length)    # prints 0
print(empty().length)         # error: Item in empty can't be worked out from its arguments: write its types after its name, empty[...](...)

A value of a type parameter is passed on: stored, put in arrays and hashes, returned, and compared with ==. To do more with it, the parameter requires a trait, with with, and then has what the trait gives:

generic-requires.hem
trait Named
  readable const name: String

  def label(): String
    return "<#{self.name}>"
  end
end

class Pet
  with Named
end

class Rock
  readable const weight: Int
end

def labels[Item with Named](items: [Item]): [String]
  return items.map do (item): String
    return item.label()
  end
end

print(labels([new Pet(name: "Rex")]))    # prints ["<Rex>"]
print(labels([new Rock(weight: 3)]))     # error: Item in labels must be something that takes on Named; Rock isn't
  • with Record requires a record, any record.
  • Each use gets its own copy, made for its types before the program runs: an Int stays a plain number, in the VM and in native code alike.
  • A class's method can have type parameters of its own, after its name: def keyed[Key](key: Code[(Row): Key]): [Key]. Its types come from its arguments and its object's, as a def's do; where nothing shows them, they're written after its name: Maker.empty[String]().
  • A method's name is a value where a generic wants a method's type, even one with types still to work out: new Rule(name: "positive", rule: positive) is a Rule[Thing] when positive takes a Thing.
  • A type a block given as code says is worked out from what it returns: rows.keyed do (row) ... end is a Key of whatever its return gives (or of what it says it gives, do (row): Talk).
  • Not yet: generic traits and enums, a generic class's statics, and generic records as JSON or a form's fields.