gpt4 book ai didi

scala - 编译器说我没有为 Set 指定类型(类型不匹配)

转载 作者:行者123 更新时间:2023-12-01 11:49:33 26 4
gpt4 key购买 nike

我是 scala 的新手,正在学习集合。我想将我的参数添加到集合中,然后从函数中返回它。

def singleElementSet(elem: Int): Set ={
var newSet = Set()
newSet+= elem
}

我试过了,但它给了我这样的错误:

type Set takes type parameters
- type Set takes type parameters

元素

type mismatch;  found   : elem.type (with underlying type Int)  required: Nothing

最佳答案

在您的示例中,您必须通过 Set[Int] 定义 Set 中包含的内容。创建新 Set 时,您必须像这样指定它的类型:

val newSet = Set.empty[Int]

或者用一些东西初始化集合:

val newSet = Set(1)

但是,您可能不得不使用 var 或可变 Set 来完成很多工作。例如,您的代码应如下所示:

var newSet = Set.empty[Int]
def singleElementSet(elem: Int): Set[Int] = {
newSet+= elem
}

(不能每次调用方法都将Set定义为空Set,否则结果不相加)

关于scala - 编译器说我没有为 Set 指定类型(类型不匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734813/

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