...

/

Introduction to Annotation Classes

Introduction to Annotation Classes

Explore Kotlin annotations, their usage, and the role of annotation processing in libraries and frameworks.

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