Unit.scala 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package models
  2. class ConversionException(from: Unit, to: Unit) extends
  3. RuntimeException(s"Cannot convert from $from to $to.", null)
  4. sealed trait Unit {
  5. def productPrefix: String
  6. protected def conversion: Float
  7. def name: String = this.productPrefix.split("\\.").last
  8. protected def abreviation: String
  9. def measure: Measure
  10. def convertToPrimary(v: Float): Float = v/conversion
  11. def convertFromPrimary(v: Float): Float = v*conversion
  12. def convertTo(v: Float, other: Unit) = {
  13. if (measure == other.measure)
  14. other.convertFromPrimary(convertToPrimary(v))
  15. else
  16. throw new ConversionException(this, other)
  17. }
  18. }
  19. case object Gram extends Unit
  20. {
  21. protected val conversion: Float = 1f
  22. val measure: Measure = Mass
  23. val abreviation: String = "g"
  24. }
  25. case object Kilogram extends Unit
  26. {
  27. protected val conversion: Float = 0.001f
  28. val measure: Measure = Mass
  29. val abreviation: String = "kg"
  30. }
  31. case object Ounce extends Unit
  32. {
  33. protected val conversion: Float = 0.03527396f
  34. val measure: Measure = Mass
  35. val abreviation: String = "oz"
  36. }
  37. case object Pound extends Unit
  38. {
  39. protected val conversion: Float = 0.00220462249993f
  40. val measure: Measure = Mass
  41. val abreviation: String = "lb"
  42. }
  43. case object Mililiter extends Unit
  44. {
  45. protected val conversion: Float = 1000f
  46. val measure: Measure = Volume
  47. val abreviation: String = "mL"
  48. }
  49. case object Liter extends Unit
  50. {
  51. protected val conversion: Float = 1f
  52. val measure: Measure = Volume
  53. val abreviation: String = "L"
  54. }
  55. case object Teaspoon extends Unit
  56. {
  57. protected val conversion: Float = 202.8842218965f
  58. val measure: Measure = Volume
  59. val abreviation: String = "tsp"
  60. }
  61. case object Tablespoon extends Unit
  62. {
  63. protected val conversion: Float = 67.627891024f
  64. val measure: Measure = Volume
  65. val abreviation: String = "Tbsp"
  66. }
  67. case object Cup extends Unit
  68. {
  69. protected val conversion: Float = 4.166666f
  70. val measure: Measure = Volume
  71. val abreviation: String = "cups"
  72. }
  73. case object Gallon extends Unit
  74. {
  75. protected val conversion: Float = 0.26417290088f
  76. val measure: Measure = Volume
  77. val abreviation: String = "gallons"
  78. }
  79. case object Count extends Unit
  80. {
  81. protected val conversion: Float = 1f
  82. val measure: Measure = Number
  83. val abreviation: String = ""
  84. }