Amethyst for Java developers
Let’s start with something familiar. Amethyst’s complex enums are Java enums: a fixed set of instances, each built by a constructor, with fields and methods. The spec even uses the planets example. You know the one.
After that, things get less familiar. Amethyst runs on .NET rather than the JVM, ends
blocks with end, and doesn’t make you write a getter for anything. There are no checked
exceptions either. We’re sorry for your loss.
Hello, world
Section titled “Hello, world”public class Main { public static void main(String[] args) { System.out.println("Hello, world!"); }}def main: Void puts "Hello, world!"endJava 25 finally lets you leave the class out too. Welcome to the club.
Each case of a complex enum is a single instance, created at startup with the arguments you give it, just like a Java enum constant.
enum Planet { MERCURY(3.303e+23, 2.4397e6), VENUS(4.869e+24, 6.0518e6), EARTH(5.976e+24, 6.37814e6);
private final double mass; private final double radius;
Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
double surfaceGravity() { return 6.67300E-11 * mass / (radius * radius); }}
Planet.EARTH.surfaceGravity();enum Planet Mercury(3.303e+23, 2.4397e6) Venus(4.869e+24, 6.0518e6) Earth(5.976e+24, 6.37814e6)
getter mass: Float getter radius: Float
def initialize(@mass: Float, @radius: Float) end
def surface_gravity: Float 6.67300e-11 * @mass / (@radius ** 2) endend
Planet.earth.surface_gravityCases are declared in PascalCase and used in snake_case. Enums without data are
plain .NET enums, and both kinds work in case/when with a .earth shorthand. See
Enums.
Classes, without the getters
Section titled “Classes, without the getters”property declares a field with a getter and a setter, and getter declares one with
only a getter. You don’t write either method. C# callers see ordinary .NET properties.
public class User { private String name; private final int age;
public User(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; }
public static User guest() { return new User("Guest", 0); }}
User user = new User("Ada", 36);class User property name: String getter age: Int
def initialize(name: String, age: Int) @name = name @age = age end
def self.guest: User User.new("Guest", 0) endend
user = User.new("Ada", 36)extends becomes <, abstract class is spelled the same, and so is implements.
There’s no record. A struct gets a constructor generated
from its fields, but nothing generates equals or hashCode for you.
Variables
Section titled “Variables”Assignment declares a variable with its type inferred, like Java’s var. Names in
ALL_CAPS are constants, standing in for static final.
var name = "Ada";int count = 0;static final int MAX_RETRIES = 3; // in a classname = "Ada"count: Int = 0MAX_RETRIES = 3No checked exceptions
Section titled “No checked exceptions”There’s no throws clause, and the compiler never makes you catch anything. Exceptions
are .NET exceptions, raised with raise and caught with rescue. Whether that’s
freedom or negligence is between you and your tests.
try { parse(path);} catch (FileNotFoundException e) { log(e.getMessage());} finally { cleanup();}begin parse(path)rescue FileNotFoundException => e log e.messageensure cleanupendInstead of try-with-resources, call use on anything Disposable, .NET’s
equivalent of AutoCloseable. It closes the resource when the block finishes, however
it finishes:
StreamReader.new("data.csv").use do |reader| puts reader.read_to_endendSee Error Handling for the rest.
Streams
Section titled “Streams”Collection methods come from Enumerable[T] and work on any
collection directly. There’s no .stream() at the start and no .toList() at the end.
List<String> names = users.stream() .filter(User::isActive) .sorted(Comparator.comparing(User::getName)) .map(User::getName) .toList();names = users.select(&:active?).sort_by(&:name).map(&:name)| Streams | Amethyst |
|---|---|
filter |
select (or reject for the opposite) |
map |
map |
flatMap |
flat_map |
reduce |
reduce |
sorted(Comparator.comparing(…)) |
sort_by |
Collectors.groupingBy |
group_by |
anyMatch / allMatch / noneMatch |
any? / all? / none? |
findFirst |
first (returns T?) |
limit / skip |
take / drop |
Optional becomes T?
Section titled “Optional becomes T?”Types are non-nullable by default. A value that might be missing has a nullable type,
T?, and a nil check narrows it. &. takes the place of a chain of Optional.map
calls.
String city = findUser(id) .map(User::getAddress) .map(Address::getCity) .orElse(null);city = find_user(id)&.address&.cityWith null safety on, which is the default, forgetting a nil check is a compile error
rather than a NullPointerException at runtime.
Interfaces become protocols
Section titled “Interfaces become protocols”A protocol is an interface, default methods
included.
interface Shape { double area();
default String describe() { return "Area: " + area(); }}
class Square implements Shape { … }protocol Shape def area: Float
def describe: String "Area: #{area}" endend
class Square implements Shape # ...endswitch becomes case
Section titled “switch becomes case”case/when is an expression. There’s no fall-through and no break, and matching on
a type narrows the value in that branch, like a type pattern.
double area = switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.width() * r.height(); default -> 0.0;};area = case shape when Circle then Math::PI * shape.radius ** 2 when Rectangle then shape.width * shape.height else 0.0 endGenerics that stay
Section titled “Generics that stay”.NET keeps generic type arguments at runtime, so there’s no type erasure. Array[Int]
holds Int values directly. There’s no Integer and no boxing.
| Java | Amethyst |
|---|---|
List<Integer> |
Array[Int], which is a .NET List<int> |
Map<String, Integer> |
Hash[String, Int] |
<T extends Comparable<T>> |
[T < Comparable[T]] |
Everything else
Section titled “Everything else”| Java | Amethyst |
|---|---|
package com.example.models; |
namespace Example::Models |
import com.example.models.*; |
use Example::Models |
static |
def self. |
this / super.method() |
self / super.method |
null |
nil |
x -> x * 2 |
{ |x| x * 2 }, or ->(x: Int) { x * 2 } |
User::getName |
&:name |
"Hello, " + name |
"Hello, #{name}" |
throw new IllegalStateException("oops") |
raise InvalidOperationException, "oops" |
@Deprecated |
@[Obsolete], the .NET attribute |
| Maven and Gradle | project.am and NuGet |
| The JVM | .NET |