繁体   English   中英

Scala:改进的代数数据类型

[英]Scala: Refined Algebraic Data Types

o/

这可能是一个相当有趣的问题,并且可能会激发你们的创造力。

我想以一种我可以的方式对货币进行建模:

  • 类型上的模式匹配(=> 代数数据类型)
  • 在其中存储一个数字金额
  • 使用精炼类型将值限制为正值,例如val amount: Float Refined Positive
  • 有一个三字符的货币代码,如“USD”,它是预定义的且不可变的

在一个实现中执行此操作的一个子集很容易,但我发现创建一种允许类似以下内容的类型非常困难:

def doSomething(currency: Currency): Unit {
  currency match {
    case BITCOIN => println("Oh, a cryptocurrency! And it is ${currency.amount} ${currency.code}!"
    case EURO => println("So we are from Europe, eh?")
  }
}

doSomething(new Currency.BITCOIN(123f)) // yielding "Oh, a cryptocurrency! And it is 123 BTC!"

val euro = new Currency.EURO(-42f) // compile error

我希望我清楚地表达了我的意图。 如果有图书馆这样做,我很高兴有人指出它,尽管我希望从自己的思考中学到一些东西。

你的意思是这样的吗?

import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.NonNegative
import eu.timepit.refined.string.MatchesRegex

sealed trait Currency extends Product with Serializable {
  def amount: Currency.Amount
  def code: Currency.Code
}

object Currency {
  type Amount = BigDecimal Refined NonNegative
  type Code = String Refined MatchesRegex["[A-Z]{3}"]

  final case class Euro(amount: Amount) extends Currency {
    override final val code: Code = "EUR"
  }

  final case class Dollar(amount: Amount) extends Currency {
    override final val code: Code = "USD"
  }
}

def doSomething(currency: Currency): Unit =
  currency match {
    case Currency.Euro(amount) => println(s"Euro: € ${amount}")
    case _ => println(s"Somenthing else with code ${currency.code} and amount ${currency.amount}")
  }

这有效:

doSomething(Currency.Dollar(BigDecimal(10))) 
// Somenthing else with code USD and amount 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM