gpt4 book ai didi

编译器和运行时之间的 Scala 类型不一致?

转载 作者:行者123 更新时间:2023-12-01 23:52:12 25 4
gpt4 key购买 nike

java.util.ArrayList 转换为 scala.collection.immutable.List,2.10 编译器和运行时似乎不一致,关于类型val 发出:

import org.ahocorasick.trie._
import scala.collection.JavaConverters._ // convert Java colllections to Scala ones

object wierd {

val trie = new Trie

def trieInit(patterns: List[String]) {
trie.onlyWholeWords();
for (pattern <- patterns)
trie.addKeyword(pattern)
}

def patternTest(text : String) : List[String] =
{
val emitsJ = trie.parseText(text)
val emits = emitsJ.asScala map (i => i.getKeyword)

println(s"converted from ${emitsJ.getClass} to ${emits.getClass}")

//return(emits)
return (List.empty[String])
}

trieInit(List("hello"))
patternTest("hello")
}

产量:

从类 java.util.ArrayList 转换为类 scala.collection.immutable.$colon$colon

现在通过仅更改 return 行更改为返回实际值 -

import org.ahocorasick.trie._
import scala.collection.JavaConverters._ // convert Java colllections to Scala ones

object wierd {

val trie = new Trie

def trieInit(patterns: List[String]) {
trie.onlyWholeWords();
for (pattern <- patterns)
trie.addKeyword(pattern)
}

def patternTest(text : String) : List[String] =
{
val emitsJ = trie.parseText(text)
val emits = emitsJ.asScala map (i => i.getKeyword)

println(s"converted from ${emitsJ.getClass} to ${emits.getClass}")

return(emits)
//return (List.empty[String])
}

trieInit(List("hello"))
patternTest("hello")
}

产生编译错误:

[error] reproduce.scala:23: type mismatch;
[error] found : Iterable[String]
[error] required: List[String]
[error] return(emits)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed

对此的简单解释是什么?我怎样才能更好地处理转化?

最佳答案

JavaConverters 转换为最接近它已拉皮条的 Java 集合的 Scala 集合。您仍然需要调用 toList 将其进一步转换为您想要的集合:

val emits = emitsJ.asScala.toList map (i => i.getKeyword)

参见相关:What is the difference between JavaConverters and JavaConversions in Scala?

关于编译器和运行时之间的 Scala 类型不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com