Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
array
integer
communitycreator

How to create an integer array using the int keyword in Scala

Theodore Kelechukwu Onyejiaku

Overview

In Scala, we can easily create an array of integers using the new keyword. We need to call the new keyword to create an array.

Syntax

var ArrayVariable = new Array[Int](numberOfElements)
Syntax for creating an integer array using new keyword

Parameters

  • ArrayVariable: This is the array variable that will be initialised with some elements.
  • Int: This parameter specifies that the array must be of type integer.
  • numberOfElements: This is the number of elements in an array.

Return value

We use the new keyword to convert the array variable to an array instance. We use the int to specify type integer. This means that any of its elements must be an integer.

Example

object Main extends App {
  // create array of integers with "new" keyword
  var OurArray = new Array[Int](3);
  OurArray(0) = 10;
  OurArray(1) = 3;
  OurArray(2) = 1;
  
  // print out array values separated by commas
  println(OurArray.mkString(","));
}
Creating an array with the new keyword in Scala

Explanation

  • line 3–6: We create an array called ourArray by using the keyword new.
  • line 9: We use the mkString() method to print the elements of the array in form of a string separated by commas.

RELATED TAGS

scala
array
integer
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring