Jock Documentation
  • Introduction to Jock
  • Getting Started
  • Language Basics
  • Operators and Expressions
  • Functions
  • Control Flow
  • Data Structures
  • Classes and Objects
  • Compiler
  • Hoon Interface
  • Nock Interface
  • Language Reference
    • ASCII
  • Tutorial
Powered by GitBook
On this page
Export as PDF

Classes and Objects

A class is a type definition intended to be used for instances or objects. It contains a basic definitional type for its state and a number of methods

Syntactically, a class requires the following elements:

  1. class keyword

  2. Type name, beginning with a capital letter

  3. Methods in a {} “sel”/“ser” block.

Like a function, a method defines a mapping from an input value to an output value. However, it does not begin with a func keyword.

compose
  class Point(x:@ y:@) {
    add(p:(x:@ y:@)) -> Point {
      (x + p.x
       y + p.y)
    }
    sub(p:(x:@ y:@)) -> Point {
      (x - p.x
       y - p.y)
    }
    scale(p:@) -> Point {
      (hoon.mul(p x)
       hoon.mul(p y))
    }
  };

let pt = Point(100 100);
pt = pt.add(50 80);
pt = pt.sub(20 15);
pt = pt.scale(50);
pt.state

Since a method only occurs within a class context, there is no syntactic ambiguity in defining them.

Syntactically, a method requires the following elements:

  1. Method name (all lower case)

  2. In parentheses, one or more arguments (the state)

  3. -> mapping operator

  4. Output type (see note)

  5. In braces, code block of body

    1. One or more methods

While a terminating ; “mic” is not required, a class is very frequently introduced using a compose statement which requires a ; “mic” to end its context definition.

A method which returns its class type returns an updated instance of the object.

Thus foo(p:(x:@ y:@)) -> Point would result in an instance, but foo(p:(x:@ y:@)) -> (@ @) would result in a cell or 2-tuple of atoms.

PreviousData StructuresNextCompiler

Last updated 23 days ago