-1

I was told that in Scala the return keyword was optional, I can write it or not (as for ;), no matter for the compiler

Please have a look at the following code:

  case class Data(x:Int)

  def test(data: List[Data]): List[Data] = {
    val newdata: List[Data] = data
      .map(d => {
        val newdx = d.x * 2
        return Data(newdx)
      })
    return newdata
  }

It doesn't compile, because of the return statement.

Putting the same logic, also with return, in the main method, actually compile and works.

So, what is the semantic of return?

besil
  • 1,308
  • 1
  • 18
  • 29
  • It's not idiomatic to use `return` in Scala. Just write it as `data.map(d => d.x * 2)`. – Eric Nov 18 '16 at 11:48

3 Answers3

3

I'm not completely sure, but reading the error I would assume the following:

In this case, the return Data(newdx) returns from the test-function. The functions returns a list, while the return-statement returns da Data object.

when you don't write return, each value is mapped like intended, the list is created and returned.

You can remove the return from return newdata, since this is the last statement, which then returns your list.

Thomas Böhm
  • 1,456
  • 1
  • 15
  • 27
1

A return expression return e must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in a source program, f , must have an explicitly declared result type, and the type of e must conform to it. The return expression evaluates the expression e and returns its value as the result of f . The evaluation of any statements or expressions following the return expression is omitted.

Avoid using return in Scala. Using return is not functional programming (it voilates the principles of functional programming).

Your code can be re-written as

def test(data: List[Data]): List[Data] = data.map(elem => Data(elem.x * 2))

More information about return in lambda function is here Use of return

Community
  • 1
  • 1
Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
1

AFAIK In Scala, if there is no return then the last expression will be the return value.

In your map by writing return explicitly will cause error and so by simply keeping the expression the value appends to List referencing the .map

Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38