pedrorijo91
pedrorijo91

Reputation: 7845

Add method to companion object through implicits

With typical classes, you can create an implicit class to add new methods to other class instances, just like this:

 implicit class IntWrapper(i: Int) {
    def otherMethod(s: String) = println(s"i: ${i} with ${s}")
  }

now you can do

3.otherMethod("something")

My questions are

  1. is it possible to add a method to the to the Int companion object? (Answered here)

  2. Imagine there's a Java enum defined out of your project, and you are using it in your Scala code. Java enums have the .valueOf(s: String) method that gets an enumeration value from a String, but that throws an IllegalArgumentException. I would like to add a method .safeValueOf(s: String) that would return an Option.

    Is it possible to do add that method to a Java enum in the same way we can do in the first example?

Upvotes: 0

Views: 230

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

Here is what you can do for 2 (approximate, untested):

import scala.reflect.ClassTag
import scala.util.Try

object SafeValueOf {
  def apply[E <: Enum[E]](s: String)(implicit tag: ClassTag[E]): Option[E] =
    Try(Enum.valueOf(tag.runtimeClass.asInstanceOf[Class[E]], s)).toOption
}

Usage: SafeValueOf[MyEnum]("something").

Upvotes: 1

Related Questions