1

In a situation similar to this

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

How would I add something to the list? What does something with type (Int,String) look like? I tried doing things similar to list+=(5,"hello") but nothing I tried worked.

0

2 Answers 2

4

I find the existing answer distracting. It doesn't explain what the problem is, which is simply that the parenthesis are being interpreted as parameter parenthesis, not tuple parenthesis. Look here:

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

The first time fails because you are calling the method += with two parameters, instead of calling it with one parameter that is a tuple.

The second time works because I used -> to denote the tuple.

The third time works because I put the extra tuple-parenthesis to denote the tuple.

That said, calling the Set a list is bad, because people would tend to think it is a List.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this was what I was looking for, I kept getting errors like in your example and wasn't sure how to get rid of them.
0

Not entirely sure what you are exactly looking for but here are some examples of adding a type of abc to a list which also includes the REPL output.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.