Last active
August 28, 2016 14:59
-
-
Save kittinunf/bddf5c103bcf2c2afda539418f41fb89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//without phantom type | |
enum class Currency { JPY, THB } | |
data class Money(val amount: Double, val currency: Currency) | |
class IllegalCurrencyException : Throwable("Wrong currency") | |
fun convertJPYToTHB(jpy: Money): Money { | |
//check whether we have right format | |
when(jpy.currency) { | |
Currency.JPY -> { | |
val exchangeRate = 0.34 | |
val convertedAmount = jpy.amount * exchangeRate | |
return Money(convertedAmount, Currency.THB) | |
} | |
else -> throw IllegalCurrencyException() | |
} | |
} | |
//usage | |
val convertedMoney: Money | |
try { | |
convertedMoney = convertJPYToTHB(Money(10000.0, Currency.JPY)) | |
} catch (e: IllegalCurrencyException) { | |
// :'( | |
} | |
//with phantom type | |
interface Currency {} | |
enum class JPY : Currency | |
enum class THB : Currency | |
data class Money<C : Currency>(val amount: Double) | |
fun convertJPYToTHB(jpy: Money<JPY>): Money<THB> { | |
val exchangeRate = 0.34 | |
return Money(amount = jpy.amount * exchangeRate) | |
} | |
//usage | |
val moneyInBaht = convertJPYToTHB(Money<JPY>(10000.0)) //compile | |
val moneyInYen = convertJPYToTHB(Money<THB>(10000.0)) //not compile | |
println(moneyInBaht) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment