繁体   English   中英

使用Scala case类构造函数作为方法调用时类型不匹配

[英]Type mismatch when using Scala case class constructor as a method call

在定制XML格式解析器上,我实现了一个简单的案例类:

case class CustomNode(tree: XmlTree)(implicit val filename: String) { ... }

在另一个调用中,我构造了该类的对象,如下所示:

implicit val filename: String = ...
val tree: XmlTree = ...

val nodes: Seq[CustomNode] =
  tree.descendant
    .filter(CustomXml.isCustomNode)
    .map(CustomNode(_))

这按预期工作正常。 但是, CustomNode(_)调用看起来很尴尬,因此我将其转换为方法值,即:

val nodes: Seq[CustomNode] =
  tree.descendant
    .filter(CustomXml.isCustomNode)
    .map(CustomNode) // <-- changed

但这会导致编译错误:

Error:(23, 12) type mismatch;
 found   : CustomNode.type
 required: XmlTree => ?
      .map(CustomNode)

我使用SBT 1.1.1版和Scala 2.12.4版进行构建。

这仅仅是一个表面问题,但我仍然想知道第二通电话怎么了。

顺便说一句,我的IDE(IntelliJ IDEA)也建议对第一个版本进行此更改,而对后一个版本看起来还不错。

关于StackOverflow以及其他与类似问题有关的地方,存在许多问题,但是我找不到遇到此特定问题的任何问题。

您正在将伴随对象作为参数传递。 与所有单例对象一样,其类型为CustomNode.type

使用.apply方法的方式略有不同。

val nodes: Seq[CustomNode] =
     tree.descendant
       .filter(CustomXml.isCustomNode)
       .map(CustomNode.apply)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM