2016-11-16 40 views
1

我是新来的斯卡拉,我需要一个结构,我可以轻松地添加新的个人访问常量,并遍历所有这些。 事情是这样的:斯卡拉:个人访问常量列表

object Constants { 
    val A = Something(...) 
    val B = Something(...) 
    val C = Something(...) 
    // ... 

    val listOfConstants = (A, B, C, ...) 
} 

但是,而不需要不断手动添加到列表中。 我认为是一个地图,这将使它更难访问常量 我结束了写这个:

def getElements[T : ClassTag](c : Any) : Set[T] = { 
    var result : Set[T] = Set() 
    for (field <- c.getClass.getDeclaredFields) { 
     field.setAccessible(true) 
     field.get(c) match { 
      case t: T => result += t 
      case _ => 
     } 
    } 
    result 
} 

,然后使用下面这行结构,这样

val listOfConstants = getElements[Something](Constants) 

这是一个脏解决方案?有更好的选择吗?

回答

2

尝试枚举,例如http://www.scala-lang.org/api/current/scala/Enumeration.htmlHow to model type-safe enum types?。你也可以用Java写你的枚举并在Scala中使用它,例如,这里是一个用Java定义的枚举,你可以在Scala中使用它 - 并且附带一个包含所有可能值的映射,所以你可以通过键,迭代值等。值的映射是自动构建的,因此不需要手动维护。

import java.util.Collections; 
import java.util.Map; 
import java.util.HashMap; 

/** 
* Demonstrates parsing of an enum from the contained value 
*/ 
public enum WithFrom implements Something { 
    TWO("one plus 1"), SIX("two plus 4"); 

    WithFrom(String expr) { 
     this.expr = expr; 
    } 

    private final String expr; 

    public static final Map<String, WithFrom> fromValue = Collections 
      .unmodifiableMap(new HashMap<String, WithFrom>() { 
       private static final long serialVersionUID = 7205142682214758287L; 

       { 
        for (WithFrom wf : WithFrom.values()) { 
         put(wf.expr, wf); 
        } 
       } 
      }); 
} 
+0

感谢您的回答,但对我来说'Something'是一个抽象类从A,B,C,......可以是多种亚型。据我所知,枚举不能被扩展。 – ChrisU

+0

Java枚举可以实现一个接口。这会有帮助吗? – radumanolescu

3

你可以使用scala的默认Enumeration,但它有它自己的caveats。我知道的最好的焚化库是Enumeratum。它可以让你写这样的事情:

object MyEnum extends Enum[Something] { 

    val values = findValues 

    case object A extends Something 
    case object B extends Something 
    case object C extends Something 
    case object D extends Something 

} 

findValues是宏自动查找在编译时的Something(内MyEnum)的所有子对象。

要添加使用SBT此lib目录下:

libraryDependencies += "com.beachape" %% "enumeratum" % "1.4.0"