0
我有以下的scala代碼。我不明白爲什麼這些隱含的東西沒有被編譯器弄明白。我也嘗試在Main中放置導入線。但請注意,隱式對象是內部主要創建時,那麼代碼正確運行Scala:無法從對象中找到隱式
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]
所有我想do做一個可插入的類型類。而不是改變任何一段代碼,僅改變導入語句以具有不同的副作用
移動至底部或使隱式類型顯式化:'隱式val DogWithLogging:Action [Dog] = new WithLogging [Dog] {...}'。 –