如何使用 scala 类型别名 (Int, String)

How to use scala type alias (Int, String)

情况与此类似

type abc=(Int,String)
val list=mutable.set[abc]()

我如何向列表中添加内容?类型为 (Int,String) 的东西是什么样的? 我尝试做类似于 list+=(5,"hello") 的事情,但我尝试过的都不起作用。

不完全确定您到底在寻找什么,但这里有一些将 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))

我觉得现有的答案让人分心。它没有解释问题是什么,只是括号被解释为参数括号,而不是元组括号。看这里:

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