繁体   English   中英

如何使用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")但没有任何尝试。

我发现现有答案令人分心。 它没有解释问题所在,只是将括号解释为参数括号,而不是元组括号。 看这里:

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是不好的,因为人们会倾向于认为SetList

不能完全确定您要查找的内容,但是这里有一些向列表中添加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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM