Scala类型类隐式解析
发布时间:2020-12-16 18:37:03  所属栏目:安全  来源:网络整理 
            导读:(斯卡拉2.11.8) 请考虑以下代码: object ScalaTest extends App { class Wrapper { import Wrapper._ def init(): Unit = { // "could not find implicit value for parameter tc: ScalaTest.Wrapper.TC[Int]" printWithTC(123) // Compiles printWithTC(12
                
                
                
            | 
                         
 (斯卡拉2.11.8) 
  
  
请考虑以下代码: object ScalaTest extends App {
  class Wrapper {
    import Wrapper._
    def init(): Unit = {
      // "could not find implicit value for parameter tc: ScalaTest.Wrapper.TC[Int]"
      printWithTC(123)
      // Compiles
      printWithTC(123)(IntTC)
      // Compiles again!
      printWithTC(132)
    }
  }
  object Wrapper {
    trait TC[A] {
      def text(a: A): String
    }
    implicit object IntTC extends TC[Int] {
      override def text(a: Int) = s"int($a)"
    }
    def printWithTC[A](a: A)(implicit tc: TC[A]): Unit = {
      println(tc.text(a))
    }
  }
  (new Wrapper).init()
} 
 关于这段代码,我有很多问题: >为什么IntTC首先没有得到解决? 解决方法
 使用具有显式返回类型的val.见 
 https://github.com/scala/bug/issues/801和 
 https://github.com/scala/bug/issues/8697(以及其他). 
  
        隐式对象与隐式val和defs具有相同的问题,具有推断的返回类型.至于你的第二个问题:当显式使用IntTC时,你强制编译器对它进行类型检查,所以在那之后它的类型是已知的并且可以通过隐式搜索找到. class Wrapper {
  import Wrapper._
  def init(): Unit = {
    // Compiles
    printWithTC(123)
    // Compiles
    printWithTC(123)(IntTC)
    // Compiles
    printWithTC(132)
  }
}
object Wrapper {
  trait TC[A] {
    def text(a: A): String
  }
  implicit val IntTC: TC[Int] = new TC[Int] {
    override def text(a: Int) = s"int($a)"
  }
  def printWithTC[A](a: A)(implicit tc: TC[A]): Unit = {
    println(tc.text(a))
  }
} 
 如果你真的希望像对象那样懒惰地对你的隐式进行求值,你可以使用带有显式类型的隐式延迟val. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
推荐文章
            站长推荐
            
        热点阅读
            