Built-in Support for String -> Trait?

自闭症网瘾萝莉.ら 提交于 2019-12-11 10:55:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!