1

我有一个看起来如下的方法:

def myMethod[T](klazz:Class[T]):Z

我想创建一个类型的 Map ,Int => () => Z以便在我的代码中,我可以在地图上查看以仅生成Z我需要的 s 。

但是,如果我执行以下操作:

Map( 0 -> myMethod(classOf[String]) _ , 1 -> myMethod(classOf[StringBuilder]))

我怎样才能避免写作() => myMethod(classOf[String])

4

2 回答 2

4

为什么不简单地改变myMethod,让它返回一个函数呢?

def myMethod( clazz: Class[_]): () => Z = {
  { () => /* put the body of the old myMethod here */ }
}

然后你可以这样做:

Map( 0 -> myMethod(classOf[String]) , 1 -> myMethod(classOf[StringBuilder]))
于 2013-03-06T15:04:45.903 回答
3

另一种方法是使用自定义关联器:

implicit class LazyMapArrow[K](val self: K) extends AnyVal {
  def ~>[V](other: => V): (K, () => V) = (self, () => other)
}
于 2013-03-06T19:13:52.063 回答