Unit.scala 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package models
  2. class ConversionException(from: Unit, to: Unit) extends
  3. RuntimeException(s"Cannot convert from $from to $to.", null)
  4. class Unit(
  5. val name: String,
  6. abreviation: String,
  7. conversion: Float,
  8. val measure: Measure
  9. ) {
  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. /*
  20. case object Gram extends Unit
  21. {
  22. protected val conversion: Float = 1f
  23. val measure: Measure = Mass
  24. val abreviation: String = "g"
  25. }
  26. case object Kilogram extends Unit
  27. {
  28. protected val conversion: Float = 0.001f
  29. val measure: Measure = Mass
  30. val abreviation: String = "kg"
  31. }
  32. case object Ounce extends Unit
  33. {
  34. protected val conversion: Float = 0.03527396f
  35. val measure: Measure = Mass
  36. val abreviation: String = "oz"
  37. }
  38. case object Pound extends Unit
  39. {
  40. protected val conversion: Float = 0.00220462249993f
  41. val measure: Measure = Mass
  42. val abreviation: String = "lb"
  43. }
  44. case object Mililiter extends Unit
  45. {
  46. protected val conversion: Float = 1000f
  47. val measure: Measure = Volume
  48. val abreviation: String = "mL"
  49. }
  50. case object Liter extends Unit
  51. {
  52. protected val conversion: Float = 1f
  53. val measure: Measure = Volume
  54. val abreviation: String = "L"
  55. }
  56. case object Teaspoon extends Unit
  57. {
  58. protected val conversion: Float = 202.8842218965f
  59. val measure: Measure = Volume
  60. val abreviation: String = "tsp"
  61. }
  62. case object Tablespoon extends Unit
  63. {
  64. protected val conversion: Float = 67.627891024f
  65. val measure: Measure = Volume
  66. val abreviation: String = "Tbsp"
  67. }
  68. case object Cup extends Unit
  69. {
  70. protected val conversion: Float = 4.166666f
  71. val measure: Measure = Volume
  72. val abreviation: String = "cups"
  73. }
  74. case object Gallon extends Unit
  75. {
  76. protected val conversion: Float = 0.26417290088f
  77. val measure: Measure = Volume
  78. val abreviation: String = "gallons"
  79. }
  80. case object Count extends Unit
  81. {
  82. protected val conversion: Float = 1f
  83. val measure: Measure = Number
  84. val abreviation: String = ""
  85. }
  86. */