Skip to content

Instantly share code, notes, and snippets.

@jonasabreu
Created January 30, 2014 22:21
Show Gist options
  • Save jonasabreu/8721275 to your computer and use it in GitHub Desktop.
Save jonasabreu/8721275 to your computer and use it in GitHub Desktop.
package aux
object Scaladores extends App {
implicit class AddOf(val num : Int) extends AnyVal {
def of[T <: MeasureUnit] = Value[T](num)
}
trait MeasureUnit
trait x[A <: MeasureUnit, B <: MeasureUnit] extends MeasureUnit
trait /[A <: MeasureUnit, B <: MeasureUnit] extends MeasureUnit
class m extends MeasureUnit
class km extends MeasureUnit
class cm extends MeasureUnit
class s extends MeasureUnit
case class Value[T <: MeasureUnit](num : Int) extends AnyVal {
def *[O <: MeasureUnit](other : Value[O]) = Value[T x O](num * other.num)
def as[O <: MeasureUnit](implicit conversor : Conversor[T, O]) : Value[O] =
conversor.converte(this)
def as[O <: MeasureUnit, K <: MeasureUnit](implicit conversor : Conversor[T, K],
converso : Conversor[K, O]) : Value[O] =
converso.converte(conversor.converte(this))
}
abstract class Conversor[F <: MeasureUnit, T <: MeasureUnit](fator : Int) {
def converte(f : Value[F]) : Value[T] = Value[T](f.num * fator)
}
implicit object FromKMtoM extends Conversor[km, m](1000)
implicit object FromMtoCm extends Conversor[m, cm](100)
implicit object FromMMtoCmCM extends Conversor[m x m, cm x cm](10000)
type `m/s^2` = m / (s x s) // /[m, x[s, s]] problema!
type `m/s^2 2` = (m / s) / s // /[/[m, s], s] problema!
val a = 2.of[m]
println(a)
println(a.as[cm])
val b : Value[m x m] = 2.of[m] * 2.of[m]
println(b)
println(b.as[cm x cm])
val c = 2.of[km]
println(c)
println(c.as[cm, m])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment