1

I'm trying to write some string utils to be able to do implicit conversions of the form "myString".doSpecialConversion and have a specialValue based on which doSpecialConversion works.

Attempt-1: Use a trait:

trait ConversionUtils {

  // Need an overridable value                                                                                                                                                                                                                                                 
  lazy val specialValue = ","

  implicit class StringConversions(val s: String) {
    def doSpecialConversion: Option[String] = if (s == specialValue) None else Some(s)
  }
}

Trait works just fine but the problem is that its not static so multiple StringConversions will be created which is undesired. So I try to extend AnyVal which can't be done for a trait because Another limitation that is a result of supporting only one parameter to a class is that a value class must be top-level or a member of a statically accessible object.

Attempt-2: Use a singleton:

object ConversionUtils {

  // Need an overridable value                                                                                                                                                                                                                                                 
  lazy val specialValue = ","

  implicit class StringConversions(val s: String) extends AnyVal {
    def doSpecialConversion: Option[String] = if (s == specialValue) None else Some(s)
  }
}

Question: How do I provide a Util to be able to override the specialValue for StringConversions and be true-ly static?

1 Answer 1

1

You can ask for an implicit parameter:

object ConversionUtils {

  case class SpecialValue(str: String)

  implicit class StringConversions(val s: String) extends AnyVal {
    def doSpecialConversion(implicit sv: SpecialValue): Option[String] = if (s == sv.str) None else Some(s)
  }
}

Usage:

scala> implicit val sp = SpecialValue(",")
sp: ConversionUtils.SpecialValue = SpecialValue(,)

scala> "aaa".doSpecialConversion
res0: Option[String] = Some(aaa)

scala> ",".doSpecialConversion
res1: Option[String] = None

In general case, macro-libraries, like machinist might help to get rid of boilerplate.

Sign up to request clarification or add additional context in comments.

Comments

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.