构建具有多个领域的创建类的简明方法?

时间:2015-08-01 20:22:31

标签: scala

给出一个案例类:

scala> case class Foo(a: String, b: String, c: String, d: String, 
                       e: String, f: Int, g: String, h: String, i: Int)
defined class Foo

我有一个功能:f: Foo => Int,我需要测试f(Foo) == 1

为了测试目的,是否有一种简洁的方法来创建案例类(不定义每个字段)?

我考虑过对该字段进行延迟评估,然后使用???,但是:

scala> case class Bar(a: => Int)
<console>:1: error: `val' parameters may not be call-by-name
case class Foo(a: => Int)
                  ^

修改

我要求的答案不包含默认参数。

3 个答案:

答案 0 :(得分:2)

不确定这样的东西是否符合您的要求,但是:

% sbt                                                                                                     
...
> set scalaVersion := "2.11.7"
...
> set libraryDependencies += "org.cvogt" %% "scalacheck-extensions" % "0.2"
...
> console
Welcome to Scala version 2.11.7 (...)
...

scala> case class Foo(a: String, b: String, c: String, i: Int)
defined class Foo

scala> import org.cvogt.scalacheck.GenTree
import org.cvogt.scalacheck.GenTree

scala> case class Foo(a: String, b: Double, c: Int)
defined class Foo

scala> GenTree.partialTree[Foo].sample
res0: Option[Foo] = Some(Foo(ᐊ沄⎤...,8.646125633001667E248,0))

awwwww yeah

答案 1 :(得分:1)

您可以为所有参数指定默认值,并使用您想要的参数创建Foo

case class Foo(a : String = "", b : String = "", c : String = "" ... )

然后,您可以使用所有默认值

创建Foo
val f = Foo()

或创建具有特定参数的

val f = Foo(a = "a", b = "b")   // the rest will have the default values

答案 2 :(得分:1)

我不明白你为什么要排除默认值,但是如果你需要为每个构建一个Foo实例的情况需要不同的默认值,那么我认为,你需要的是一个工厂对象。这样的事情可能是:

object FooFactory {
  def apply(a: String): Foo = Foo(a, "b", ... "k", 1)
  def apply(b: String): Foo = Foo("a1", b, ... "k1", 2)
  //add an apply overload for every combination you need
}