Amethyst for Kotlin developers
Kotlin and Amethyst agree on more than you’d expect from a language that ends its
blocks with end. Types are non-nullable by default, String? means what you think
it means, and the compiler narrows a value once you’ve checked it. And Amethyst’s DSLs
are Kotlin’s type-safe builders with Ruby’s syntax. You’ll recognise them. We certainly
did.
The big difference is underneath. Kotlin mostly runs on the JVM, and Amethyst runs on .NET. Your Gradle muscle memory won’t help you here, though nothing else would either.
Hello, world
Section titled “Hello, world”fun main() { println("Hello, world!")}def main: Void puts "Hello, world!"endBuilders
Section titled “Builders”A Kotlin lambda with a receiver, HTML.() -> Unit, is an Amethyst
receiver block, () -> Void with HtmlBuilder.
The receiver moves from the front of the type to a with at the end, and yield
passes it in.
fun html(init: HTML.() -> Unit): HTML { val html = HTML() html.init() return html}
val page = html { h1("Shopping list") ul { li("Eggs") li("Milk") }}def html(&block: () -> Void with HtmlBuilder): HtmlBuilder builder = HtmlBuilder.new yield builder builderend
page = html do h1 "Shopping list" ul do li "Eggs" li "Milk" endendA receiver block can take arguments too: (Product) -> Void with RowBuilder is
Kotlin’s RowBuilder.(Product) -> Unit. See
Type-safe builders for a full walkthrough.
Variables
Section titled “Variables”There’s no val and no var, in the Kotlin sense. Assignment declares a variable with
its type inferred, and assigning again changes it. Names in ALL_CAPS are constants.
val name = "Ada"var count: Int = 0count += 1const val MAX_RETRIES = 3name = "Ada"count: Int = 0count += 1MAX_RETRIES = 3Functions
Section titled “Functions”fun becomes def, and the body ends with end instead of a brace. The last
expression is the return value, so there’s no need for = or return. A public
method without a return type returns nil and compiles to void, much like Unit.
fun square(x: Int): Int = x * x
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
greet("Ada", greeting = "Kia ora")def square(x: Int): Int x * xend
def greet(name: String, greeting:: String = "Hello"): String "#{greeting}, #{name}!"end
greet("Ada", greeting: "Kia ora")Kotlin lets you pass any argument by name. Amethyst splits parameters in two:
positional ones, written name: Type, and keyword ones, written name:: Type, which
must be passed by name. See Parameter Kinds.
Null safety
Section titled “Null safety”This part should feel like home. T? is nullable, T isn’t, and a nil check narrows
the type inside the branch, like a smart cast. ?. is spelled &..
val user = findUser(id) // User?if (user != null) { println(user.name) // smart cast to User}val city = user?.address?.cityuser = find_user(id) # User?if user puts user.name # narrowed to Userendcity = user&.address&.city # String?There’s no !!, so you can’t tell the compiler to trust you. There’s no ?: either.
Check for nil and let the compiler narrow the type.
if only accepts a Bool or a nullable value, so if user is a nil check, and
if count doesn’t compile when count is an Int.
Classes
Section titled “Classes”Primary constructors become initialize. Writing @ in front of a parameter name
declares the field and assigns it, so def initialize(@name: String) does the job of
class User(private val name: String). property and getter play the parts of
public var and val properties. The companion object becomes methods defined on
self.
class User(var name: String, val age: Int) { companion object { fun guest() = User("Guest", 0) }}
val user = 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)There’s no data class. A struct gets a constructor generated
from its fields, but nothing generates copy, equals or hashCode for you.
Properties from other languages
Section titled “Properties from other languages”Kotlin tidies up Java for you: getValue() and setValue(v) turn into x.value and
x.value = v. Amethyst does the same sort of tidying for .NET. A C# property Value
is read as x.value and written as x.value = v, and snake_case names find their
PascalCase members. See Method and Property Casing.
when becomes case
Section titled “when becomes case”when becomes case/when, and it’s still an expression. Matching on a type narrows
the value in that branch, like is.
val label = when (value) { 1, 2, 3 -> "small" in 4..10 -> "medium" is String -> "a string: $value" else -> "unknown"}label = case value when 1, 2, 3 then "small" when 4..10 then "medium" when String then "a string: #{value}" else "unknown" endThere are no sealed classes, and case never checks that you’ve covered every
case. Keep the else.
Extensions
Section titled “Extensions”Extension functions become an extension class,
which can hold as many methods as you like. They’re visible where they’re defined, and
can be imported with use.
fun String.isPalindrome(): Boolean = this == this.reversed()extension class String def palindrome?: Bool self == self.reverse endendpalindrome? compiles to IsPalindrome, so Java… sorry, C# callers get the name
they’d expect.
Coroutines
Section titled “Coroutines”suspend fun becomes async def. The difference is that Amethyst makes you say
await where Kotlin doesn’t, and it all runs on .NET tasks rather than coroutines.
suspend fun fetch(url: String): String { val response = client.get(url) return response.bodyAsText()}async def fetch(url: String): String response = await http.get(url) await response.read_bodyendEverything else
Section titled “Everything else”| Kotlin | Amethyst |
|---|---|
package com.example.models |
namespace Example::Models |
import com.example.models.* |
use Example::Models |
List<String> |
Array[String], which is a mutable .NET List<string> |
listOf(1, 2, 3) |
[1, 2, 3] |
mapOf("a" to 1) |
{ "a" => 1 } |
"Hello, $name" |
"Hello, #{name}" |
{ it * 2 } |
{ |x| x * 2 }, or ->(x: Int) { x * 2 } |
users.map { it.name } |
users.map(&:name) |
filter |
select |
1 until 10, 1..<10 |
1...10 |
<T : Comparable<T>> |
[T < Comparable[T]] |
Unit |
Void, or Nil |
Nothing |
Never |
Any |
Any |
interface with default methods |
protocol with default implementations |
throw |
raise |
try … catch … finally |
begin … rescue … ensure … end |
reader.use { … } |
reader.use { |r| … }, on anything Disposable. Same name, same idea |
@Serializable |
@[Serializable] |
| Gradle and Maven Central | project.am and NuGet |