How to create an empty list in Dart - list

I want to create an empty list for a Flutter project.
final prefs = await SharedPreferences.getInstance();
final myStringList = prefs.getStringList('my_string_list_key') ?? <empty list>;
I seem to remember there are multiple ways but one recommended way. How do I do it?

There are a few ways to create an empty list in Dart. If you want a growable list then use an empty list literal like this:
[]
Or this if you need to specify the type:
<String>[]
Or this if you want a non-growable (fixed-length) list:
List.empty()
Notes
In the past you could use List() but this is now deprecated. The reason is that List() did not initialize any members, and that isn't compatible with null safe code. Read Understanding null safety: No unnamed List constructor for more.
Effective Dart Usage Guide

Fixed Length List
var fixedLengthList = List<int>.filled(5, 0);
fixedLengthList[0] = 87;
Growable List
var growableList = [];
growableList.add(499);
For more refer Docs

I had this problem as well when I tried List.empty();, but just initializing a list to [] works and makes it append-able.

Related

Arrow Java ListVector writeBatch and read get empty list

I have a ListVector and value [[1,2,3,4,5]] in VectorSchemaRoot and I could see its value in IDEA.
I use following code to write the VectorSchemaRoot variable and get the byte array
val out = new ByteArrayOutputStream()
val writer = new ArrowStreamWriter(vectorSchemaRoot, null, out)
writer.start()
writer.writeBatch()
writer.end()
out.close()
val byteArr = out.toByteArray
And read back
val allocator = new RootAllocator(Int.MaxValue)
val reader = new ArrowStreamReader(new ByteArrayInputStream(byteArr), allocator)
while (reader.loadNextBatch()) {
val schemaRoot = reader.getVectorSchemaRoot
schemaRoot
}
The schema is correct, but the list is empty []
However, I use other types of values, like char, bit, the result read from the byteArr is correct(non-empty).
How to fix the ListVector empty issue?
Finally I used just basic classes.
The StructVector, ListVector are complex classes, and according to my test, they do not bring speed or memory benefit over just using basic classes. And the documents for complex classes are very few.
Thus basic classes is recommended. And just use List of Fields to make the schema of them, could also get the structured vector.

how can I use the copy method for case classes on a list of that case class?

I have a list of records (record is a case class). I am trying to simultaneously update all of the records in the list (using the copy function) and return a list of the updated records.
I tried to use a foreach method but it's not allowing me to produce the list as a result.
This is what I tried so far, I'm not sure if any of this is right
def update_record(record: List[Rec]): List[Rec] = {
val result = record.foreach(r => {
r.copy(firstname = get_firstname(r, record), lastname = get_lastname(r, record))
})
result
}
but result doesn't produce a list so I'm not sure what to do now.
You just need to use map instead of foreach.
def update_record(record: List[Rec]: List[Rec] =
record.map { r =>
r.copy(firstname = get_firstname(r, record), lastname = get_lastname(r, record))
}
Anyways, it would be good to follow some tutorial or course or read a book about the language. This is just basic knowledge of the standard library.
Some links that may be useful:
Scala tour.
Scala book.
Scaladoc.
Scala style guide.

Scala. foreach in one element Lists of Dates

I want to create a function that works on a single date or over a period of time. For that I make a list of strings like this:
import com.github.nscala_time.time.Imports._
val fromDate = "2015-10-15".toLocalDate
val toDate = "2015-10-15".toLocalDate
val days = Iterator.iterate(fromDate)(_ + 1.day).takeWhile(_ <= toDate).map(_.toString)
Now I want to access days content:
scala> days.foreach(println)
2015-10-15
scala> days.foreach(day => println(day))
With the first foreach I get the only element in days list, but with the second I get nothing. This is just a sample, but I need to use the 2nd form, because I need to use day value inside the function.
If I use a range both methods work like they are supposed to...
Anyone knows why this behaviour?
Thanks in advance!
P.D. I don't want to use another method to create the list of strings (unless I can't find a solution for this)
Second function works in same way as first.
You've created Iterator object, which you can iterate only once.
To be able use it any amount of times just convert you iterator to list.
val daysL = days.toList

Convert a Java List of Lists to Scala without O(n) iteration?

Answers to this question do a good job of explaining how to use Scala's Java Converters to change a Java List into a Scala List. Unfortunately, I need to convert a List of Lists from Java to Scala types, and that solution doesn't work:
// pseudocode
java.util.List[java.util.List[String]].asScala
-> scala.collection.immutable.List[java.util.List[String]]
Is there a way to do this conversion without an O(N) iteration over the Java object?
You need to convert the nested lists as well, but that would require the up front O(n):
import scala.collection.JavaConverters._
val javaListOfLists = List(List("a", "b", "c").asJava, List("d", "e", "f").asJava).asJava
val scalaListOfLists = javaListOfLists.asScala.toList.map(_.asScala.toList)
Alternatively, you could convert the outer list into a Stream[List[T]], that would only apply the conversion cost as you accessed each item
val scalaStreamOfLists = javaListOfLists.asScala.toStream.map(_.asScala.toList)
If you don't want to pay the conversion cost at all, you could write a wrapper around java.util.List which would give you a scala collection interface. a rought shot at that would be:
def wrap[T](javaIterator: java.util.Iterator[T]): Stream[T] = {
if (javaIterator.hasNext)
javaIterator.next #:: wrap(javaIterator)
else
empty
}
val outerWrap = wrap(javaListOfLists.iterator).map(inner => wrap(inner.iterator()))
alternatively you can use scalaj-collection library i wrote specifically for this purpose
import com.daodecode.scalaj.collection._
val listOfLists: java.util.List[java.util.List[String]] = ...
val s: mutable.Seq[mutable.Seq[String]] = listOfLists.deepAsScala
that's it. It will convert all nested java collections and primitive types to scala versions. You can also convert directly to immutable data structures using deepAsScalaImmutable (with some copying overhead of course)

Scala: Create new list of same type

I'm stuck and the solutions Google offered me (not that many) didn't work somehow. It sounds trivial but kept me busy for two hours now (maybe I should go for a walk...).
I've got a list of type XY, oldList: List[XY] with elements in it. All I need is a new, empty List of the same type.
I've already tried stuff like:
newList[classOf(oldList[0])]
newList = oldList.clone()
newList.clear()
But it didn't work some how or takes MutableList, which I don't like. :/
Is there a best (or any working) practice to create a new List of a certain type?
Grateful for any advice,
Teapot
P.S. please don't be too harsh if it's simple, I'm new to Scala. :(
Because empty lists do not contain anything, the type parameter doesn't actually matter - an empty List[Int] is the same as an empty List[String]. And in fact, they are exactly the same object, Nil. Nil has type List[Nothing], and can be upcast to any other kind of List.
In general though when working with types that take type parameters, the type parameter for the old value will be in scope, and it can be used to create a new instance. So a generic method for a mutable collection, where the type parameter matters even if empty:
def processList[T](oldList: collection.mutable.Buffer[T]) = {
val newList = collection.mutable.Buffer[T]()
// Do something with oldList and newList
}
There are probably nicer solutions, but from the top of my head:
def nilOfSameType[T](l: List[T]) = List.empty[T]
val xs = List(1,2,3)
nilOfSameType(xs)
// List[Int] = List()
if you want it to be empty, all you should have to do is:
val newList = List[XY]()
That's really it, as long as I'm understanding your question.