Skip to content

Instantly share code, notes, and snippets.

@koizumihiroo
Created July 11, 2019 09:33
Show Gist options
  • Save koizumihiroo/22cbe4a08edc9c6b4d2507c9f8ec43e0 to your computer and use it in GitHub Desktop.
Save koizumihiroo/22cbe4a08edc9c6b4d2507c9f8ec43e0 to your computer and use it in GitHub Desktop.
inline class Currency<T>(private val value: Double) {
operator fun plus(c2: Currency<T>): Currency<T> = Currency(value + c2.value)
operator fun minus(c2: Currency<T>): Currency<T> = Currency(value - c2.value)
operator fun times(c2: Currency<T>): Currency<T> = Currency(value * c2.value)
operator fun div(c2: Currency<T>): Currency<T> = Currency(value / c2.value)
operator fun unaryPlus(): Currency<T> = this
operator fun unaryMinus(): Currency<T> = Currency(-value)
fun toDouble(): Double = value
}
class Usd; class Jpy
fun main() {
val u1 = Currency<Usd>(12.3)
val u2 = Currency<Usd>(2.34)
val j1 = Currency<Jpy>(12.3)
val j2 = Currency<Jpy>(333.0)
println(u1 + u2)
println(j1 + j2)
// Why this returns `true` ?
println(u1 == j1)
// Error
// println(u1 + j2)
}
@koizumihiroo
Copy link
Author

import java.math.BigDecimal

inline class Currency<T>(private val value: BigDecimal) {
    operator fun plus(c2: Currency<T>): Currency<T> = Currency(value + c2.value)
    fun toDouble(): Double = value.toDouble()
}

class Usd; class Jpy

fun main() {

    val u1 = Currency<Usd>((10).toBigDecimal())
    val u2 = Currency<Usd>("20".toBigDecimal())
    val j1 = Currency<Jpy>(10.toBigDecimal())
    val j2 = Currency<Jpy>(100.toBigDecimal())
    println(u1 + u2)
    println(j1 + j2)
    // Error
    // println(u1 + j1)
    println(u1 == j1)
    println(u1 ===  j1)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment