我有以下scala函数,我不会编译,因为它发现Unit甚至很难它需要[SomethingElse]
def combine(trees: List[CodeTree]): List[CodeTree] = {
if(trees.length < 2) trees
else isortForTrees(trees.+:(new Fork(trees.head, trees.tail.head, chars(trees.head).:::(chars(trees.tail.head)), weight(trees.head) + weight(trees.tail.head))))
def isortForTrees(myList: List[CodeTree]): List[CodeTree] = {
if(myList.isEmpty) Nil
else insertForTrees(myList.head, isortForTrees(myList.tail))
}
def insertForTrees(toBeInserted: CodeTree, lisToBe: List[CodeTree]): List[CodeTree] = {
if(lisToBe.isEmpty || weight(toBeInserted) < weight(lisToBe.head)) toBeInserted :: lisToBe
else lisToBe.head :: insertForTrees(toBeInserted, lisToBe.tail)
}
}
我无法理解为什么要归还一个单位? if语句的两端都返回一个List [CodeTree]。这可能是我犯的一个愚蠢的错误,但我根本找不到它。我在这里缺少什么?
答案 0 :(得分:3)
方法中的最后一个表达式是返回Unit
的方法定义。只需移动
if(trees.length < 2) trees
else isortForTrees(trees.+:(new Fork(trees.head, trees.tail.head, chars(trees.head).:::(chars(trees.tail.head)), weight(trees.head) + weight(trees.tail.head))))
到方法的底部,它应该可以工作。