【问题标题】:defining a simple implicit Arbitary定义一个简单的隐式 Arbitrary
【发布时间】:2012-04-03 10:55:00
【问题描述】:

我有一个类型Foo,其构造函数采用Int。如何为 Foo 定义一个 implicit Arbitrary 以与 scalacheck 一起使用?

implicit def arbFoo: Arbitrary[Foo] = ???

我想出了以下解决方案,但它对我的口味来说有点过于“手动”和低级:

val fooGen = for (i <- Gen.choose(Int.MinValue, Int.MaxValue)) yield new Foo(i)

implicit def arbFoo: Arbitrary[Foo] = Arbitrary(fooGen)

理想情况下,我想要一个高阶函数,我只需要插入一个Int =&gt; Foo 函数。


我设法将其缩减为:

implicit def arbFoo = Arbitrary(Gen.resultOf((i: Int) => new Foo(i)))

但我仍然觉得必须有一个稍微简单一点的方法。

【问题讨论】:

    标签: unit-testing scala generator implicit scalacheck


    【解决方案1】:

    好吧,您可以使用下划线表示法,而不是将整个 Foo-creating 函数定义为 (i: Int) =&gt; new Foo(i))

    class Foo(i: Int)
    
    (1 to 3).map(new Foo(_))
    

    这是可行的,因为 Scala 知道 Foo 接受 Int,并且 map 映射到 Ints,因此无需明确说明。

    所以这有点短:

    implicit def arbFoo = Arbitrary(Gen.resultOf(new Foo(_)))
    

    【讨论】:

    • 其实案例类在 Scala 中是作为函数处理的,所以你可以写得更简单:implicit def arbFoo = Arbitrary(Gen.resultOf(Foo))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2011-07-10
    相关资源
    最近更新 更多