简体   繁体   中英

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

Working on a custom XML format parser, I have implemented a simple case class:

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

In another call, I construct objects of that class like this:

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

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

This works fine as expected. However, the CustomNode(_) call looks awkward, so I converted it into a method value, ie:

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

This results in a compile error though:

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

I use SBT version 1.1.1 and Scala version 2.12.4 to build.

This is merely a cosmetic issue, but I am still wondering what is wrong with the second call.

BTW, my IDE (IntelliJ IDEA) also suggests this change for the first version, whereas the latter version looks fine to it.

There are many questions on StackOverflow and other places that are related to similar points, but I could not find any that has encountered this specific issue.

You are passing the companion object as a parameter. Its type is CustomNode.type as with all singleton objects.

A slightly different way is user the .apply method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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