在类似的情况下
type abc=(Int,String)
val list=mutable.set[abc]()
我如何在列表中添加内容?类型(Int,String)的外观是什么样的?
我尝试过与list+=(5,"hello")
类似的事情,但我没有尝试过任何工作。
答案 0 :(得分:4)
我发现现有的答案令人分心。它没有解释问题是什么,简单地说,括号被解释为参数括号,而不是元组括号。看这里:
scala> list+=(5,"hello")
<console>:10: error: type mismatch;
found : Int(5)
required: abc
(which expands to) (Int, String)
list+=(5,"hello")
^
<console>:10: error: type mismatch;
found : String("hello")
required: abc
(which expands to) (Int, String)
list+=(5,"hello")
^
scala> list+=(5 -> "hello")
res1: list.type = Set((5,hello))
scala> list+=((5,"hello"))
res2: list.type = Set((5,hello))
第一次失败是因为你用两个参数调用方法+=
,而不是用一个参数作为元组调用它。
第二次有效,因为我使用->
来表示元组。
第三次起作用是因为我把额外的元组括号用来表示元组。
也就是说,调用Set
一个list
是不好的,因为人们会倾向于认为它是List
。
答案 1 :(得分:0)
不完全确定您正在寻找什么,但这里有一些将abc类型添加到列表中的示例,该列表还包括REPL输出。
type abc = (Int, String)
defined type alias abc
scala> val item : abc = (1, "s")
item: (Int, String) = (1,s)
// i.e. Creating a new abc
scala> val item2 = new abc(1, "s")
item2: (Int, String) = (1,s)
scala> val list = List(item, item2)
list: List[(Int, String)] = List((1,s), (1,s))
// Shows an explicit use of type alias in declaration
val list2 = List[abc](item, item2)
list2: List[(Int, String)] = List((1,s), (1,s))
// Adding to a mutable list although immutable would be a better approach
scala> var list3 = List[abc]()
list3: List[(Int, String)] = List()
scala> list3 = (5, "hello") :: list3
list3: List[(Int, String)] = List((5,hello))
// Appending abc (tuple) type to mutable list
scala> list3 = list3 :+ (5, "hello")
list3: List[(Int, String)] = List((5,hello), (5,hello))