Examples Overview¶
This section provides practical examples of Onion programs, demonstrating various language features and programming patterns.
Example Programs¶
All examples can be found in the run/ directory of the Onion repository.
Basic Programs¶
- Hello World - Simple output
- Arrays - Array manipulation
- User Input - Reading input
Object-Oriented Examples¶
- Classes and Objects - Basic OOP
- Inheritance - Extending classes
- Interfaces - Interface implementation
Functional Programming¶
- Lambda Expressions - Anonymous functions
- Closures - Capturing variables
- Recursion - Recursive algorithms
Practical Use-Cases¶
- Scripting & CLI - Command-line arguments, process execution, file I/O
- JSON & HTTP - JSON/YAML parsing, HTTP client basics
- Async & Concurrency - Futures, async composition, do-notation
- Error Handling - Option, Result, validation patterns
Running Examples¶
Using the Script Runner¶
Compiling and Running¶
Example Index¶
| File | Description | Topics Covered |
|---|---|---|
Hello.on |
Hello World | Basic I/O |
Array.on |
Array operations | Arrays, loops |
StringCat.on |
String concatenation | Strings, arrays |
ReadLine.on |
User input | I/O, strings |
List.on |
Dynamic lists | ArrayList, << operator |
Foreach.on |
Foreach loop | Iteration, collections |
Select.on |
Pattern matching | Select expression |
LineFilter.on |
Lambda filtering | Lambdas, closures |
LineCounter.on |
File processing | Recursion, I/O |
Factorial.on |
Recursion | Recursive functions |
Primes.on |
Sieve of Eratosthenes + factorization | Boolean arrays, for/while loops |
Delegation.on |
Delegation pattern | Interfaces, forward |
Calculator.on |
GUI calculator | Swing, event handling |
Bean.on |
JavaBean pattern | Serialization, getters/setters |
OrderReport.on |
Larger data pipeline | Records, enums, collection pipelines |
DeptReport.on |
CSV group-by/aggregate pipeline | Csv, records, Maps::groupBy, Stats |
ExprEval.on |
Expression evaluator | Interfaces, polymorphism |
AdtExpr.on |
Expression evaluator, as an ADT enum | enum case cases, select, exhaustiveness |
StatsApp.on |
Statistics processing | Generics, extension methods |
TodoManager.on |
Task manager | Records, enums, extension methods |
ShapeProcessor.on |
Geometry shapes | Inheritance, extension methods |
TextAnalyzer.on |
Text statistics | String/List extension methods |
WordStats.on |
Word-frequency text statistics | Strings, Maps::countBy, records |
LogSummary.on |
Shape-first log analysis | record ... from re"...", Maps::countBy |
ConfigApp.on |
CLI + config file | Args, YAML, derive!(Yaml) |
JsonApiClient.on |
JSON + HTTP client | Http, Json, records |
AsyncDownloader.on |
Concurrent futures | Future, do-notation |
ShellPipeline.on |
Shell process pipeline | Proc, file I/O |
ResultValidation.on |
Validation with errors | Option, Result |
StaticImports.on |
Static method imports | import { Class::method } |
UnitConverter.on |
CLI unit converter | Extension methods, Args |
SetOperations.on |
Set algebra | onion.Sets (union, intersection, difference) |
PrimitivePredicate.on |
Filtering with a primitive predicate | java.util.function.Predicate[Int], removeIf |
PrimitiveFunctionalInterfaces.on |
Primitive-typed Java functional interfaces | Predicate, Supplier, Function with primitive type args |
SortWithPrimitiveComparator.on |
Sorting with a primitive comparator | java.util.Comparator[Int], primitive lambda bridging |
CollectionUtilities.on |
Map/list utilities | onion.Maps, onion.Iterables, custom sort |
FizzBuzz.on |
Classic FizzBuzz | Loops, modulo, conditionals |
Fibonacci.on |
Recursive vs. iterative Fibonacci | Recursion, loops, Timing |
DataClass.on |
Record equals/hashCode/copy demo |
Records, toString, copy |
Bidirectional.on |
One record, every direction | from re"...", derive!(Json, Yaml), example |
CsvProcessor.on |
CSV header parsing + aggregation | Csv::parseWithHeader |
CliArgsDemo.on |
Manual CLI argument parsing | onion.Args |
FileWordCounter.on |
Word count from a file | File I/O, BufferedReader |
Generics.on |
Generic box class | Generic classes, type parameters |
PairSample.on |
Generic pair class | Generic classes, multiple type parameters |
Extension.on |
Extension methods on a built-in type | extension blocks |
NullSafety.on |
Nullable types and safe navigation | T?, ?. safe call operator |
ValVarInference.on |
val/var type inference |
Local type inference, mutable vs. immutable |
PrimitivePrint.on |
Printing primitives | IO::println/IO::print |
FunctionTypesSample.on |
Function-typed parameters | Function types, lambdas |
JavaCollectionsSample.on |
Java collections interop | java.util.ArrayList, Collections |
JavaGenerics.on |
Java generics interop | java.util.ArrayList[String] |
GuessNumber.on |
Number-guessing game | BufferedReader, control flow |
TodoApp.on |
Interactive CLI todo list | ArrayList, console I/O |
HttpJsonClient.on |
HTTP + JSON client | onion.Http |
RegexLogParser.on |
Log line parsing | re"..." regex select patterns |
RecordLaws.on |
Record law/example clauses |
law, example, compile-time checking |
SchemePrefix.on |
User-definable scheme-prefixed literals | prefix"..." raw string literals |
ShapeFirst.on |
Shape-first scripting tour | re"...", pipelines, do-notation, auto-CLI |
FixedWidthDemo.on |
User-written Shape instance |
onion.Shape, Outcome/Defect, law |
JsonYamlShapeDemo.on |
Named JSON/YAML shape on a record | shape name = json/yaml |
ConfigEditDemo.on |
Lossless config editing | Lens, Residue, comment/order preservation |
BrokenLogDemo.on |
Partial-failure log parsing | onion.Shape, Outcome::values/defects |
ToolDemo.on |
CLI derived from a tool declaration |
tool, capabilities, --help/--contract/--plan |
Learning Path¶
Beginner¶
- Start with
Hello.on- Basic syntax - Try
Array.on- Data structures - Explore
Foreach.on- Iteration
Intermediate¶
- Study
Factorial.on- Recursion - Learn
LineFilter.on- Lambdas - Review
Bean.on- OOP patterns - Try
UnitConverter.on- Extension methods and CLI args
Advanced¶
- Analyze
Calculator.on- GUI programming - Understand
Delegation.on- Design patterns - Examine
LineCounter.on- File processing
Practical¶
ConfigApp.on- Build a CLI-driven config loaderJsonApiClient.on- Parse JSON and call HTTP APIsAsyncDownloader.on- Run tasks concurrentlyShellPipeline.on- Orchestrate shell commandsResultValidation.on- Handle errors functionally
Next Steps¶
- Basic Examples - Simple programs
- OOP Examples - Object-oriented code
- Functional Examples - Functional programming
- Scripting Examples - CLI and process automation
- JSON & HTTP Examples - Network and data formats
- Async Examples - Concurrent programming
- Error Handling Examples - Validation and errors