简体   繁体   中英

Scala and Java Generics - Type Mismatch Error

There is a method with this signature:

public List<? extends TagNode> getElementListByName(String findName, boolean isRecursive) {
        return getElementList(new TagNodeNameCondition(findName), isRecursive);
}

In Scala I used the method like so:

val anchorNodes = bodyNode.getElementListByName("a", true)

and wrote a function to filter out all of the anchor tags with this signature:

def buildArticleLinksList(anchorTags: List[TagNode]): List[TagNode] = {
        @tailrec def buildArticlesList(articleLinksList: List[TagNode], anchorTags: List[TagNode]): List[TagNode] = anchorTags match {
            case Nil => articleLinksList
            case anchorTag :: tail if(anchorTag.getAttributeByName("href").contains(relativeCheckStr)) => buildArticlesList(articleLinksList:::List(anchorTag), tail)
        }

        buildArticlesList(List(), anchorTags)
}

but I get an error that says the following:

Type mismatch, expected: List[TagNode], actual: List[_ <: TagNode]

Could someone explain a way for me to declare my function that allows for type I am actually passing in please, it is a little confusing.

Converted the Java List to a List for Scala and it has worked.

EDIT

Though I should include the import and the code, it was an easy fix once I read the error more carefully.

To fix it I basically imported JavaConverters like so:

import scala.collection.JavaConverters._

Then I converted the Java List to a Scala list like so:

val anchorNodes = bodyNode.getElementListByName("a", true).asScala.toList

The thing here is that asScala will map the Java List to a Buffer which is Scala's equivalent, so we can then convert that to a Scala List.

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