简体   繁体   English

Scala和Java泛型-类型不匹配错误

[英]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: 在Scala中,我使用了如下方法:

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. 将Java列表转换为Scala的列表,并且可以正常工作。

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: 要修复它,我基本上是这样导入JavaConverters的:

import scala.collection.JavaConverters._

Then I converted the Java List to a Scala list like so: 然后,我将Java列表转换为Scala列表,如下所示:

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. 这里的问题是, asScala会将Java列表映射到与Scala等效的Buffer,因此我们可以将其转换为Scala列表。

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

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