【问题标题】:Make partially apply function from java function从java函数部分应用函数
【发布时间】:2011-11-26 01:39:13
【问题描述】:

我有这样的java函数

public static CollectionReader createCollectionReader(
        Class<? extends CollectionReader> readerClass, TypeSystemDescription typeSystem,
        Object... configurationData) 

我想从中创建一个部分应用函数,并为 Object... 部分指定一些参数。我不确定这是否可能。我试过了

val partiallyApply = createCollectionReader(_:Class[_ <: CollectionReader], _:TypeSystemDescription,
                                           "IncludeGoldStandardAnnotations", new Boolean("true"), 
                                           "EndIndex", new Integer("-1"), _:_*) // Doesn't work

并希望它被用作

val reader = partiallyApply(classOf[someReader], someType:TypeSystemDescription, 
"other", "configurationData", "beside", "those_four_that_already_applied_too"]

但这似乎不起作用。另外,这个对象……有技术名称吗?

编辑:稍微更改代码(我的错误..我忘记在其中输入 val 名称)并添加我想要的用法示例。

EDIT2:我认为我的主要问题是可以对 vararg 执行部分应用功能吗?

EDIT3:感谢肘部的建议。我想出了

def createCollectionReaderReadAll(cls: Class[_ <: CollectionReader], ts: TypeSystemDescription, cfg: AnyRef*) =
  createCollectionReader(cls, ts,
    Seq("IncludeGoldStandardAnnotations", new Boolean("true"), "EndIndex", new Integer("-1")) ++ cfg: _*)

工作得很好

【问题讨论】:

  • Object... 被称为varargs
  • unclear - 您是要在 scala 中创建方法定义还是要调用 java 方法?您提供的 scala 代码有多个缺陷,以缺少 val 名称开头 :-) 让我知道您要做什么,我会尽力提供帮助!顺便说一句 Object... 与 AnyRef* 相同
  • 感谢您指出这一点。我简直不敢相信我忘了把名字放在 val...
  • np :) 是否可以对 vararg 执行部分应用函数 - 不是直接,但 varargs 转换为数组,因此您应该能够传递数组。

标签: java scala partial-application


【解决方案1】:

我认为您不能部分应用可变参数,我会这样做:

def method1(x: Int, cfg: String*) = cfg
def method2(x: Int, cfg: String*) = method1(x, Seq("preset", "cfg") ++ cfg:_*)

【讨论】:

  • 错了,完全可以部分应用可变参数,例如def tag(name: String)(attrs: Tuple2[String,String]*)(body: String*) = { etc...}
  • @AlanBurlison 不幸的是,这不是我的意思,但是当我们这样做时:如何在您的示例中放置 attrs 的占位符?
  • 此外,令我惊讶的是,可以这样做:def m(xs: Int*) = xs; val f = m(1, 2, _: Int),但看起来占位符本身不能是可变参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多