使用 Scala case class 构造函数作为方法调用时类型不匹配
Type mismatch when using Scala case class constructor as a method call
使用自定义 XML 格式解析器,我实现了一个简单的案例 class:
case class CustomNode(tree: XmlTree)(implicit val filename: String) { ... }
在另一个调用中,我构造了 class 的对象,如下所示:
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) 也建议对第一个版本进行此更改,而后一个版本看起来不错。
在 Whosebug 和其他地方有很多与类似点相关的问题,但我找不到任何遇到过这个具体问题的人。
您正在将伴随对象作为参数传递。
与所有单例对象一样,它的类型是 CustomNode.type
。
用户使用 .apply
方法略有不同。
val nodes: Seq[CustomNode] =
tree.descendant
.filter(CustomXml.isCustomNode)
.map(CustomNode.apply)
使用自定义 XML 格式解析器,我实现了一个简单的案例 class:
case class CustomNode(tree: XmlTree)(implicit val filename: String) { ... }
在另一个调用中,我构造了 class 的对象,如下所示:
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) 也建议对第一个版本进行此更改,而后一个版本看起来不错。
在 Whosebug 和其他地方有很多与类似点相关的问题,但我找不到任何遇到过这个具体问题的人。
您正在将伴随对象作为参数传递。
与所有单例对象一样,它的类型是 CustomNode.type
。
用户使用 .apply
方法略有不同。
val nodes: Seq[CustomNode] =
tree.descendant
.filter(CustomXml.isCustomNode)
.map(CustomNode.apply)