Search⌘ K
AI Features

Introduction to Annotation Classes

Explore Kotlin annotation classes to understand how they add metadata to elements. Learn to create custom annotations and see how annotation processors generate additional code, enhancing libraries and testing frameworks integration.

Another special kind of class in Kotlin is annotations, which we use to provide additional information about an element. Here is an example class that uses the JvmField, JvmStatic, and Throws annotations.

Kotlin 1.5
import java.math.BigDecimal
import java.math.MathContext
class Money(
val amount: BigDecimal,
val currency: String,
) {
@Throws(IllegalArgumentException::class)
operator fun plus(other: Money): Money {
require(currency == other.currency)
return Money(amount + other.amount, currency)
}
companion object {
@JvmField
val MATH = MathContext(2)
@JvmStatic
fun eur(amount: Double) =
Money(amount.toBigDecimal(MATH), "EUR")
@JvmStatic
fun usd(amount: Double) =
Money(amount.toBigDecimal(MATH), "USD")
@JvmStatic
fun pln(amount: Double) =
Money(amount.toBigDecimal(MATH), "PLN")
}
}
fun main() {
// Create instances of Money using the provided companion object functions
val money1 = Money.eur(100.50)
val money2 = Money.eur(75.25)
// Perform addition of money amounts with the plus operator
val result = money1 + money2
// Print the result
println("Money 1: ${money1.amount} ${money1.currency}")
println("Money 2: ${money2.amount} ${money2.currency}")
println("Sum: ${result.amount} ${result.currency}")
}

The above code defines a Money class representing monetary values with amount and currency. It includes an operator fun plus for adding two Money ...