问题
Given the following:
scala> trait Foo
defined trait Foo
scala> case object Bip extends Foo
defined module Bip
scala> case object Bar extends Foo
defined module Bar
Is there any feature, built into Scala, that can make a Foo
from a String
?
example:
f("Bip")
=== Bip
f("Bar")
=== Bar
f("...")
=== Exception (or maybe returns None
)?
回答1:
You could use macros, but it may be easier to just use simple Java reflection:
namespace org.example
import scala.util.control.Exception._
object Demo extends App {
sealed trait Foo
case class Bar() extends Foo
case class Bip() extends Foo
def makeFoo(s: String): Option[Foo] = {
catching(classOf[Exception]).opt(Class.forName("org.example.Demo$" + s).newInstance.asInstanceOf[Foo])
}
println(makeFoo("Bar")) // Some(Bar())
println(makeFoo("Bip")) // Some(Bip())
println(makeFoo("Bop")) // None
}
If you put all the case classes in a single object container like I did above, the class names should be pretty predictable.
Edit: Added optional wrapper for exceptional cases.
来源:https://stackoverflow.com/questions/28784583/built-in-support-for-string-trait