Scala Replit中如何导入同目录下的自定义Scala对象?
正确导入Scala单例对象的方法及代码修复建议
一、正确的导入方式
你的两个文件处于同一根目录,且没有声明任何包名,因此不需要额外导入语句,直接在Main对象中使用TwoSum即可。如果一定要显式导入,只需写import TwoSum(但同默认包下的对象可直接访问,这行导入不是必须的)。
修正后的main.scala代码:
object Main { def main(args: Array[String]): Unit = { val twoSumResult = TwoSum.findTwoSum(Array(2,4,8,14),22) println(s"Two Sum = ${twoSumResult.mkString(",")}") } }
注:同时修复了原代码中mkstring的大小写错误(应为mkString),以及println的参数拼接问题。
二、TwoSum.scala中的代码错误修复
原代码存在多个语法和逻辑问题,即使导入正确也无法运行,以下是修正后的版本:
object TwoSum { // 显式声明返回类型为Int def sumExists(item: Int, rest: Array[Int], target: Int): Int = { if (rest.isEmpty) -1 else { val current = rest.head if (item + current == target) current else sumExists(item, rest.tail, target) } } // 显式声明返回类型为Array[Int] def findTwoSum(array: Array[Int], target: Int): Array[Int] = { if (array.length < 2) Array(-1, -1) else { val current = array.head val rest = array.tail val complement = sumExists(current, rest, target) // 修复方法名拼写错误 if (complement != -1) Array(current, complement) else findTwoSum(rest, target) // 修正递归参数,避免跳过元素 } } }
关键修复点:
- 给方法添加显式返回类型:Scala中若方法有返回值但未声明类型,编译器会推断为
Unit,导致return语句完全无效。 - 修复方法名拼写:
findTwoSum中调用的sumExist应为sumExists。 - 优化递归逻辑:原代码递归时传入
rest.tail会跳过元素,改为直接传入rest保证遍历所有可能的组合。 - 去掉冗余
return:Scala以最后一行表达式作为返回值,无需显式return。
三、运行结果
修正后运行代码,输入数组Array(2,4,8,14)和目标值22,会输出:
Two Sum = 8,14
内容的提问来源于stack exchange,提问作者Shivam Sahil
相关产品推荐
相关产品推荐

