Mohan
Mohan

Reputation: 151

Understanding Scala Syntax

I have code below and I wanted to know what does Seq[String] = List() mean? Does it mean it takes sequence of strings and converts it into List()?

def somefuncname(input: Seq[String] = List()): Unit = {
  //Some Code
}

Upvotes: 1

Views: 425

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

First try to understand the below function signature.

def somefuncname(input: Seq[String]): Unit = {
  //Some Code
}

The above code is a function declaration. Its a function which takes 1 argument called input which is of type Seq[String]. That means it takes sequence or list of strings as input and returns nothing Unit

Now, what does = mean?

= after the input argument of the function means default value for the function argument. If you are not interested in passing a custom "sequence of strings" then you can rely on the default argument of already passed.

Now, what does List() mean?

List() returns sequence of 0 elements or empty sequence. That means function is taking empty elements as default argument

alternatively you can also pass Seq() as default argument. It also means empty sequence

def somefuncname(input: Seq[String] = Seq()): Unit = {
 //Some Code
}

Now to use the function in any of the following ways

  1. somefuncname() // Now input is empty sequence of strings

  2. somefuncname(Seq("apple", "cat"))

  3. somefuncname(List("apple", "cat"))

Upvotes: 2

Arnon Rotem-Gal-Oz
Arnon Rotem-Gal-Oz

Reputation: 25939

input is of type Seq[String] and it has a default value of empty list (List()). Having a default value means so that if you call the function without passing an argument it would get the default value

Upvotes: 1

Related Questions