【发布时间】:2012-10-09 10:11:18
【问题描述】:
我希望创建一个表示数据大小(字节、KB...)的类型族。为此,我们的想法是构建一个基本类型,使其具有基于以下内容的实际尺寸:
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
有一个有序的列表:
val sizes = List(B, KB, MB, GB, TB, PB, EX, ZB, TB)
并且有一个转换方法,它接受一个目标类型,找到它们之间的索引差异,并乘以 1024 的差异幂。所以:
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)
}
}
在我检查方法的有效性之前,我遇到了一些问题(因为我是 Scala 新手):
- 有没有办法创建一个包含类型而不是值的列表(或任何其他序列)?或者更确切地说 - 类型作为值?
- 如果我理解正确,类型不会超出编译范围。这是否意味着在运行时,如果我将 GB 值传递给现有 KB,它就无法破译类型?
谢谢你, 埃胡德
【问题讨论】:
标签: scala custom-type typelist