w3resource

Scala Programming: Create a list in different ways

Scala Programming List Exercise-1 with Solution

Write a Scala program to create a list in different ways.

Note: Use Lisp style, Java style, Range list, Uniform list, Tabulate list.

Sample Solution:

Scala Code-1:

object Scala_List
{
  def main(args: Array[String]): Unit = 
 {
   println("Create a Scala List:")
   println("Lisp style:")
   val lisp_list = 100 :: 200 :: 300 :: Nil :: 400 :: Nil
   println(lisp_list)
   println("Java style:")
   val nums = List(1,2,3,4,5,6,7)
   println(nums)
   println("Mixed type values in a list:")
   val x = List[Number](100, 200, 110.20, 45d, 0x1)
   println(x)
   println("Range List:")
   val y = List.range(1, 20)
   println(y)
   val z = List.range(0, 30, 3)
   println(z)   
   println("Uniform  List:")
   val s = List.fill(5)("Scala")
   println(s)
   val n = List.fill(3)(4)
   println(n)
   println("Tabulate List:")
   val t = List.tabulate(10)(n => n * n * n)
   println(t)
  }
}

Sample Output:

Create a Scala List:
Lisp style:
List(100, 200, 300, List(), 400)
Java style:
List(1, 2, 3, 4, 5, 6, 7)
Mixed type values in a list:
List(100, 200, 110.2, 45.0, 1)
Range List:
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
List(0, 3, 6, 9, 12, 15, 18, 21, 24, 27)
Uniform  List:
List(Scala, Scala, Scala, Scala, Scala)
List(4, 4, 4)
Tabulate List:
List(0, 1, 8, 27, 64, 125, 216, 343, 512, 729)

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Scala Basic Exercises Home.
Next: Write a Scala program to add single element and multiple elements to a given listbuffer/list.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/list/scala-list-exercise-1.php