2017-07-08 9 views
0

zu finden Ich habe den folgenden Scala-Code. Ich verstehe nicht, warum das Implizite nicht vom Compiler erfunden wird. Ich habe auch versucht, die Import-Zeile in Main zu setzen. Beachten Sie jedoch, dass, wenn das implizite Objekt innerhalb Haupt erstellt wurde, dann wird der Code Scala: Nicht implizit vom Objekt

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

Ich habe richtig

lief die notwendige implizit aus dem LoggingAddon importiert, aber immer noch der scala Compiler sagt could not find implicit Action[Dog]

Alles, was ich bin versucht zu Do ist eine Pluggable-Klasse. Anstatt jedes Stück Code zu ändern, lediglich die Importanweisungen verschiedene Nebenwirkungen haben ändern

Antwort

2

einfach die Reihenfolge der Verwendung bewegen, wo implizit importiert wird, ich nach unten bewegt in folgendem Beispiel

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

Or mache den impliziten Typ explizit: 'implicit val DogWithLogging: Aktion [Hund] = new WithLogging [Hund] {...}'. –

Verwandte Themen