Scala:无法从对象中找到隐式

时间:2017-07-08 12:17:19

标签: scala implicit

我有以下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]

我要做的就是制作一个可插拔的类型类。而不是更改任何代码,只需更改import语句以产生不同的副作用

1 个答案:

答案 0 :(得分:2)

只需移动隐式导入的使用顺序,我移动到以下示例的底部

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)
  }
}