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.
stringToOption?