我不會用這裏的隱式轉換,但在課堂上結合一個觀點:
case class Foo(x: Int)
case class Bar(y: Int)
implicit def foo2Bar(foo: Foo) = Bar(foo.x)
case class Items[A <% Bar](xs: List[A]) {
def apply(x: Int): Bar = xs(x)
}
現在,您可以用Foo
列表中創建的Items
一個實例,並在內部使用它們,如果他們分別是Bar
s。
scala> Items(List(Foo(1)))
res8: Items[Foo] = Items(List(Foo(1)))
scala> res8(0)
res9: Bar = Bar(1)
編輯:
一些澄清,爲什麼我就不能使用隱式轉換:
隱式轉換可能是危險的,當他們在範圍和意外轉換的東西,他們不應該轉換。我總是會顯式地或通過視圖邊界來轉換東西,因爲那樣我就可以控制它,隱式轉換可能會縮小代碼的大小,但也會使其他人難以理解。我只會對'擴展我的圖書館'模式使用隱式轉換。
EDIT2:
您可以但是添加到集合類型的方法,做這個轉換,如果這樣的方法在範圍:
trait Convertable[M[A], A] {
def convertTo[B](implicit f: A => B): M[B]
}
implicit def list2Convertable[A](xs: List[A]) = new Convertable[List, A] {
def convertTo[B](implicit f: A => B) = xs.map(f)
}
scala> implicit def int2String(x: Int) = x.toString
int2String: (x: Int)String
scala> List(1,2,3).convertTo[String]
res0: List[String] = List(1, 2, 3)
除了在此處使用其他的隱式轉換,我可能會使用類型類型,但我認爲你有基本的想法。
它是某種標準庫的一部分嗎?我討厭重新發明輪子 – Edmondo1984 2013-02-18 17:41:12
@ Edmondo1984:不知道,我從頭開始寫了它,但我也可能重新發明輪子。順便再讀一遍我的答案,我爲此解決方案進行了整合,因此對於任何可轉換類型,只需一個'convList'隱式轉換。 – 2013-02-18 17:52:00