I am looking to create a type family that would represent data sizes (Byte, KB...). for that, the idea is to build a base type to have the real sizes based on:
type SizeUnit = Int
type B = SizeUnit
type KB = SizeUnit
type MB = SizeUnit
type GB = SizeUnit
type TB = SizeUnit
type PB = SizeUnit
type EB = SizeUnit
type ZB = SizeUnit
type YB = SizeUnit
have an ordered list of them:
val sizes = List(B, KB, MB, GB, TB, PB, EX, ZB, TB)
and have a convertion method that takes a target type, finds the index difference between them and multiplies by 1024 in the power of difference. so:
def convertTo(targetType: SizeUnit): SizeUnit ={
def power(itr: Int): Int = {
if (itr == 0) 1
else 1024*power(itr-1)
}
val distance = sizes.indexOf(targetType) - sizes.indexOf(this)
distance match {
//same type - same value
case 0 => targetType
//positive distance means larget unit - smaller number
case x>0 => targetType / power(distance)
//negative distance means smaller unit - larger number and take care of negitivity
case x<0 => targetType * power(distance) * (-1)
}
}
i have a few problems before i even check the validity of the method (as i am new to Scala):
- is there a way to create a List (or any other Seq) that holds types rather than values? or rather - types as values?
- if i understand correctly, types are not kept beyond compilation. does that mean that in runtime, if i pass a GB value to an existing KB, it cannot decipher the types?
thank you, Ehud