How to unpack items from a List?

user3308774

I'm trying to "unpack" items from a List into 4 separate vals

def myFunc(myList: List[Int]): Unit = {
    val (w,x,y,z) = myList
    // Compile error
}

If I run this, I get the following error:

Error:(16, 9) constructor cannot be instantiated to expected type;
 found   : (T1, T2, T3, T4)
 required: List[Int]
    val (w, x, y, z) = myList
        ^

So, it looks like the compiler can't infer that everything coming out of a List[Int] is actually still Ints. Is there a way to parameterize assignments like this?

Ionuț G. Stan

The problem is that you're trying to pattern match a list using a 4-tuple extractor. Try this instead:

scala> val a :: b :: c :: d :: rest = List(1, 2, 3, 4, 5, 6, 7)
a: Int = 1
b: Int = 2
c: Int = 3
d: Int = 4
rest: List[Int] = List(5, 6, 7)

scala> val (a, b, c, d) = (1, 2, 3, 4)
a: Int = 1
b: Int = 2
c: Int = 3
d: Int = 4

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to unpack pair of indexes of list items

From Dev

How to unpack optional items from a tuple?

From Dev

how to unpack the list of elements

From Dev

How to unpack this list comprehension

From Dev

zip list too many items to unpack

From Dev

How can I unpack four variables from a list?

From Dev

How can I send and unpack the list of tuples from python to qml?

From Dev

How to delete list items from list in python

From Dev

How to create list of items from another list

From Java

How to unpack a list in java to sublist

From Dev

How to unpack a list of tuples with enumerate?

From Dev

How to unpack tuples in nested list?

From Dev

How to unpack tupled list in python

From Dev

How to filter one list of items from another list of items?

From Dev

Unpack list from single line list comprehension

From Dev

How to unpack values from a file

From Dev

how can unpack a list in list comprehension

From Dev

How to get the items from adapter and store it in list?

From Dev

how to pupulate dropdown list with items from array?

From Dev

How to remove undefined from a list of items?

From Dev

How to get a single list of items from dataframe

From Dev

How to display items from a list of maps into a listview

From Python

How to insert Items from a list into QlistWidget?

From Dev

How to list directory items from a directory java

From Java

How to remove items from a list while iterating?

From Java

How to remove all duplicate items from a list

From Dev

How to emit items from a list with delay in RxJava?

From Dev

How to remove newline items from a list in Python?

From Dev

How to remove similar items from a list of lists

Related Related

HotTag

Archive