导入时(从对象)无法找到隐式参数

时间:2017-04-07 23:52:00

标签: scala implicit

为什么以下代码无法找到MyProducers的导入含义?根据我的理解,这应该可以正常工作,因为隐含在范围内。

Error:(16, 34) could not find implicit value for evidence parameter of type MyProducers.ListProducer[Int]
  val stuffInt:Int = getHead[Int]()
Error:(16, 34) not enough arguments for method getHead: (implicit evidence$2: MyProducers.ListProducer[Int])Int.
Unspecified value parameter evidence$2.
  val stuffInt:Int = getHead[Int]()
Error:(18, 43) could not find implicit value for evidence parameter of type MyProducers.ListProducer[String]
  val stuffString:String = getHead[String]()
Error:(18, 43) not enough arguments for method getHead: (implicit evidence$2: MyProducers.ListProducer[String])String.
Unspecified value parameter evidence$2.
  val stuffString:String = getHead[String]()

代码:

object Resolver {

  import MyProducers._
  import MyProducers._

  def getList[T:ListProducer]():List[T]= implicitly[ListProducer[T]].produceList


  def getHead[T:ListProducer]():T= getList[T]().head

  val stuffInt:Int = getHead[Int]()

  val stuffString:String = getHead[String]()

  val im=ip  // this compiles fine, so implicits are in scope
  val sm=sp
}

object MyProducers{
  trait ListProducer[T]{
    def produceList:List[T]
  }
  object IntProducer extends ListProducer[Int]{
    override def produceList = List(22, 42)
  }
  implicit val ip=IntProducer

  object StringProducer extends ListProducer[String]{
    override def produceList = List("stuff", "Shiraly")
  }
  implicit val sp=StringProducer
}

奇怪的是,这段代码编译得很好:

object Resolver {

  import MyProducers._
  import MyProducers._
  trait ListProducer[T]{
    def produceList:List[T]
  }
  object IntProducer extends ListProducer[Int]{
    override def produceList = List(22, 42)
  }
  implicit val ip=IntProducer

  object StringProducer extends ListProducer[String]{
    override def produceList = List("stuff", "Shiraly")
  }
  implicit val sp=StringProducer


  def getList[T:ListProducer]():List[T]= implicitly[ListProducer[T]].produceList


  def getHead[T:ListProducer]():T= getList[T]().head

  val stuffInt:Int = getHead[Int]()

  val stuffString:String = getHead[String]()

  val im=ip
  val sm=sp
}

知道为什么第一个代码在第二个代码编译时没有编译?

1 个答案:

答案 0 :(得分:3)

隐式val和defs需要对它们进行类型注释。添加这些,并找到隐含。