对字符串的内置支持 ->特征? [英] Built-in Support for String -> Trait?
本文介绍了对字符串的内置支持 ->特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于以下内容:
scala> trait Foo
defined trait Foo
scala> case object Bip extends Foo
defined module Bip
scala> case object Bar extends Foo
defined module Bar
Scala 中是否有任何功能可以从 String
生成 Foo
?
Is there any feature, built into Scala, that can make a Foo
from a String
?
示例:
f("Bip")
=== Bip
f("Bar")
=== Bar
f("...")
=== 异常(或者可能返回 None
)?
f("...")
=== Exception (or maybe returns None
)?
推荐答案
您可以使用宏,但使用简单的 Java 反射可能更容易:
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
}
如果像我上面那样将所有 case 类放在单个对象容器中,那么类名应该是非常可预测的.
If you put all the case classes in a single object container like I did above, the class names should be pretty predictable.
为特殊情况添加了可选包装器.
Added optional wrapper for exceptional cases.
这篇关于对字符串的内置支持 ->特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文