【问题标题】:How to use scala type alias (Int, String)如何使用 scala 类型别名 (Int, String)
【发布时间】:2015-06-26 00:54:48
【问题描述】:

类似的情况

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

如何在列表中添加内容?类型为 (Int,String) 的东西是什么样的? 我尝试做类似于list+=(5,"hello") 的事情,但我尝试过的没有任何效果。

【问题讨论】:

    标签: scala types type-alias


    【解决方案1】:

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

    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))
    

    第一次失败,因为您使用两个参数调用方法 +=,而不是使用一个元组参数调用它。

    第二次有效,因为我使用-&gt; 来表示元组。

    第三次有效,因为我把额外的元组括号表示元组。

    也就是说,将Set 称为list 是不好的,因为人们会倾向于认为它是List

    【讨论】:

    • 谢谢,这正是我一直在寻找的,我不断收到类似您的示例中的错误,不知道如何摆脱它们。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2018-04-21
      • 2015-04-03
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多