0

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.

2
  • where would you use stringToOption? Commented Aug 4, 2017 at 16:51
  • Edited the question to hopefully explain better. Thanks! Commented Aug 4, 2017 at 17:00

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please provide a reference confirming possible removal of implicit conversion from future versions of Scala?
@Haspemulator Added a link the relevant PR discussion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.