【问题标题】:Scala: Not able to find implicit from objectScala:无法从对象中找到隐式
【发布时间】:2017-07-08 20:27:09
【问题描述】:

我有以下 scala 代码。我不明白为什么编译器没有计算出隐式。我还尝试将导入行放在 Main 中。但是请注意,当在 Main 中创建隐式对象时,代码会正确运行

import LoggingAddon._

object Main {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    Util.act(dog)
  }
}

class Dog {
  def bark(): Unit = {
    println("woof")
  }
}

trait Action[A] {
  def action(x: A): Unit
}

trait WithoutLogging[A] extends Action[A] {
}

trait WithLogging[A] extends Action[A] {
}

object LoggingAddon {

  implicit object DogWithLogging extends WithLogging[Dog] {
    override def action(x: Dog): Unit = {
      println("before")
      x.bark()
      print("after")
    }
  }
}

object NoLoggingAddion {

  implicit object DogWithoutLogging extends WithoutLogging[Dog] {
    override def action(x: Dog): Unit = {
      x.bark()
    }
  }
}

object Util {
  def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
    nolog.action(x)
  }
}

我已经从 LoggingAddon 导入了必要的隐式,但 scala 编译器仍然显示could not find implicit Action[Dog]

我要做的就是创建一个可插入的类型类。无需更改任何代码,只需更改导入语句以产生不同的副作用

【问题讨论】:

    标签: scala implicit


    【解决方案1】:

    简单地移动导入隐式的使用顺序,我在下面的例子中移到了底部

    class Dog {
      def bark(): Unit = {
        println("woof")
      }
    }
    
    trait Action[A] {
      def action(x: A): Unit
    }
    
    trait WithoutLogging[A] extends Action[A] {
    }
    
    trait WithLogging[A] extends Action[A] {
    }
    
    object LoggingAddon {
    
      implicit object DogWithLogging extends WithLogging[Dog] {
        override def action(x: Dog): Unit = {
          println("before")
          x.bark()
          print("after")
        }
      }
    }
    
    object NoLoggingAddion {
    
      implicit object DogWithoutLogging extends WithoutLogging[Dog] {
        override def action(x: Dog): Unit = {
          x.bark()
        }
      }
    }
    
    object Util {
      def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
        nolog.action(x)
      }
    }
    
    import LoggingAddon._
    object Main {
      def main(args: Array[String]): Unit = {
        val dog = new Dog
        Util.act(dog)
      }
    }
    

    【讨论】:

    • 或者使隐式的类型显式:implicit val DogWithLogging: Action[Dog] = new WithLogging[Dog] { ... }.
    猜你喜欢
    • 2013-03-08
    • 2016-01-23
    • 1970-01-01
    • 2018-02-01
    • 2019-07-21
    • 2020-01-14
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多