Scala:隐式转换是否适用于Any?

时间:2010-09-29 22:03:18

标签: scala implicit typeclass

我想将来自不同类型层次结构的一些对象存储到List[Any]或类似容器中,但稍后会对它们执行隐式转换以执行类似类的操作。 这是一个例子:

abstract class Price[A] {
  def price(a: A): Int
}

trait Car
case class Prius(year: Int) extends Car
trait Food
case class FriedChicken() extends Food

object Def {
  // implicit object AnyPrices extends Price[Any] {
  //   def price(any: Any) = 0
  // }

  // implicit object PriusPrices extends Price[Prius] {
  //   def price(car: Prius) = 100
  // }

  implicit object CarPrices extends Price[Car] {
    def price(car: Car) = 100
  }

  implicit object FoodPrices extends Price[Food] {
    def price(food: Food) = 5
  }
}

def implicitPrice[A: Price](x: A) = implicitly[Price[A]].price(x)

import Def._  
val stuff: List[Any] = List(Prius(2010), FriedChicken())
stuff map { implicitPrice(_) }

上面的代码抛出错误如下:

error: could not find implicit value for evidence parameter of type Price[Any]
       stuff map { implicitPrice(_) }
                                ^

如果您取消注释AnyPrices,则会获得List(0,0),但这不是我所期待的。 我是否必须将清单存储到列表中才能使其生效?

此外,List(Prius(2010)) map { implicitPrice(_) }也不起作用,因为它需要Price[Prius]Price[Car]不够好。有没有办法让它更灵活?

1 个答案:

答案 0 :(得分:0)

因此,一旦对象缩减为Any,我看起来无法获得类型类。我使用Manifest的尝试也失败了,因为即使我有Any对象,我似乎也无法将T转换为Manifest[T]

import reflect.Manifest._
def add [A, B >: A](stuff: A, list: List[(B, Manifest[_])])(implicit m: Manifest[A]) = (stuff, m) :: list
val stuff2 = add(Prius(2000), add(FriedChicken(), Nil))
stuff2 map { x =>
  val casted = x._2.erasure.cast(x._1)
  implicitPrice(casted)
}

给了我

error: could not find implicit value for evidence parameter of type Price[Any]

因此,在我将其加入Price之前,似乎必须先将问题解析为List

abstract class Price[A] {
  def price(a: Any): Int
}

trait Car
case class Prius(year: Int) extends Car
trait Food
case class FriedChicken() extends Food

object Def {  
  implicit object PriusPrices extends Price[Prius] {
    def price(car: Any) = 100
  }

  implicit object FriedChickenPrices extends Price[FriedChicken] {
    def price(food: Any) = 5
  }
}

import Def._  

def add [A, B >: A](stuff: A, list: List[(B, Price[_])])(implicit p: Price[A]) = (stuff, p) :: list
val stuff = add(Prius(2000), add(FriedChicken(), Nil))
stuff map { x => x._2.price(x._1) }