Introduction to Annotation Classes
Explore Kotlin annotations, their usage, and the role of annotation processing in libraries and frameworks.
We'll cover the following...
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.
Press + to interact
import java.math.BigDecimalimport java.math.MathContextclass 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 {@JvmFieldval MATH = MathContext(2)@JvmStaticfun eur(amount: Double) =Money(amount.toBigDecimal(MATH), "EUR")@JvmStaticfun usd(amount: Double) =Money(amount.toBigDecimal(MATH), "USD")@JvmStaticfun pln(amount: Double) =Money(amount.toBigDecimal(MATH), "PLN")}}fun main() {// Create instances of Money using the provided companion object functionsval money1 = Money.eur(100.50)val money2 = Money.eur(75.25)// Perform addition of money amounts with the plus operatorval result = money1 + money2// Print the resultprintln("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 ...