Reputation: 913
I'm new to Scala and am having some trouble wrapping my mind around implicit functions.
Say I have an implicit function that turns Strings
into Option[String]
which is written
implicit def stringToOption(s: String): Option[String] = if(s.isEmpty) { None } else { Some(s) }
Then I have an XML tree that either could or could not have an attribute <thing>
I also have 2 classes which use this implicit function like such:
case class ClassA(field: Option[String])
object ClassA {
implicit val decoder(nodeSeq: NodeSeq) =>
ClassA(field = nodeSeq \@ "thing")
}
And
case class ClassB(field: Option[String])
object ClassB {
implicit val decoder(nodeSeq: NodeSeq) =>
ClassB(field = nodeSeq \@ "thing")
}
Is there a way to store the implicit function such that both of these separate classes will know to turn the String
into Option[String]
in both?
Ordinarily, I would stick in stringToOption
into one of the classes like:
case class ClassB(field: Option[String])
object ClassB {
implicit def stringToOption(s: String): Option[String] = if(s.isempty) {None} else {Some(s)}
implicit val decoder(nodeSeq: NodeSeq) =>
ClassB(field = nodeSeq \@ "thing")
}
But, I would like to stick it somewhere else so that it's available for both classes and I don't need to rewrite it as such in both. Is this possible?
Thanks in advance.
Upvotes: 0
Views: 87
Reputation: 8529
Implicit functions are considered a bad practice as they make code harder to follow and make mistakes easier. They currently require a language import to use without warnings and there is discussion to potentially heavily restrict them.
That said, it is possible to do what you ask. Define your implicit function in an object somewhere then import it where you need it.
object DangerousImplicits {
implicit def stringToOption(s: String): Option[String] = if(s.isempty) {None} else {Some(s)}
}
Now you can import this into whatever place you want this implicit conversion. (I would recommend importing within a method to minimize the scope of the import)
import DangerousImplicits.stringToOption
Upvotes: 2