如何使用伴随工厂对象作为策略? [英] How to use companion factory objects as strategy?
问题描述
当我遍历 Map
中的值时,由于排序问题,我有一个测试间歇性失败.
I have a test which fails intermittently because of ordering issues when I iterate over the values in a Map
.
Scala 提供了一个 ListMap
,它以牺牲性能为代价使测试稳定.所以我将 ImmutableMapFactory
抽象为一个 val 并在我的代码中使用它.
Scala helpfully provides a ListMap
which makes the tests stable, at the expense of performance. So I abstracted the ImmutableMapFactory
as a val and use it in my code.
class C {
val immutableMapFactory = scala.collection.immutable.Map
def func = {
...
immutableMapFactory(pairs :_*)
}
}
现在我的计划是扩展 C 并覆盖 immutableMapFactory
以进行测试
Now my plan was to extend C and override immutableMapFactory
for tests
class TestableC extends C {
override val immutableMapFactory = scala.collection.immutable.ListMap
}
不出所料,这会失败,因为 ListMap
与 Map
的类型不同.我应该如何指定 val(或 def)的类型,以便我可以在需要创建 Map 的任何地方使用工厂?
Unsurprising this fails as ListMap
does not have the same type as Map
. How should I specify the type of the val (or a def) so that I can use the factory wherever I need to create a Map?
推荐答案
你的问题在这一行:
val immutableMapFactory = scala.collection.immutable.Map
这使得 immutableMapFactory
等于单例对象 Map
.ListMap
(单例)不是Map
(单例)的子类,因此后续覆盖失败.
This makes immutableMapFactory
equal to the singleton object Map
. ListMap
(the singleton) is not a subclass of Map
(the singleton), so the subsequent override fails.
如果您改为从 Map
中获取 apply
方法,并将其部分应用以形成第一类函数(类型 (A, B)* => immutable.Map[A,B]
) 然后可以使该技术起作用:
If you instead take the apply
method from Map
, and partially apply it to form a first class function (of type (A, B)* => immutable.Map[A,B]
) then the technique can be made to work:
import collection.immutable
class Bip {
def fac[A,B] = immutable.Map.apply[A,B] _
}
class Bop extends Bip {
override def fac[A,B] = immutable.ListMap.apply[A,B] _
}
这篇关于如何使用伴随工厂对象作为策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!