Skip to content

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.

Kotlin
fun main() {
println("Hello, world!")
}
Amethyst
def main: Void
puts "Hello, world!"
end

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.

Kotlin
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
val page = html {
h1("Shopping list")
ul {
li("Eggs")
li("Milk")
}
}
Amethyst
def html(&block: () -> Void with HtmlBuilder): HtmlBuilder
builder = HtmlBuilder.new
yield builder
builder
end
page = html do
h1 "Shopping list"
ul do
li "Eggs"
li "Milk"
end
end

A receiver block can take arguments too: (Product) -> Void with RowBuilder is Kotlin’s RowBuilder.(Product) -> Unit. See Type-safe builders for a full walkthrough.

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.

Kotlin
val name = "Ada"
var count: Int = 0
count += 1
const val MAX_RETRIES = 3
Amethyst
name = "Ada"
count: Int = 0
count += 1
MAX_RETRIES = 3

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.

Kotlin
fun square(x: Int): Int = x * x
fun greet(name: String, greeting: String = "Hello") =
"$greeting, $name!"
greet("Ada", greeting = "Kia ora")
Amethyst
def square(x: Int): Int
x * x
end
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.

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 &..

Kotlin
val user = findUser(id) // User?
if (user != null) {
println(user.name) // smart cast to User
}
val city = user?.address?.city
Amethyst
user = find_user(id) # User?
if user
puts user.name # narrowed to User
end
city = 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.

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.

Kotlin
class User(var name: String, val age: Int) {
companion object {
fun guest() = User("Guest", 0)
}
}
val user = User("Ada", 36)
Amethyst
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)
end
end
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.

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/when, and it’s still an expression. Matching on a type narrows the value in that branch, like is.

Kotlin
val label = when (value) {
1, 2, 3 -> "small"
in 4..10 -> "medium"
is String -> "a string: $value"
else -> "unknown"
}
Amethyst
label = case value
when 1, 2, 3 then "small"
when 4..10 then "medium"
when String then "a string: #{value}"
else "unknown"
end

There are no sealed classes, and case never checks that you’ve covered every case. Keep the else.

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.

Kotlin
fun String.isPalindrome(): Boolean =
this == this.reversed()
Amethyst
extension class String
def palindrome?: Bool
self == self.reverse
end
end

palindrome? compiles to IsPalindrome, so Java… sorry, C# callers get the name they’d expect.

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.

Kotlin
suspend fun fetch(url: String): String {
val response = client.get(url)
return response.bodyAsText()
}
Amethyst
async def fetch(url: String): String
response = await http.get(url)
await response.read_body
end
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