0

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?

Community
  • 1
  • 1
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82

1 Answers1

1

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").

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487