0

Why i am getting this type annotation difference in these below scenarios. For scenario 1

case class TestData(name : String , idNumber : Int)
val createRandomData : immutable.IndexedSeq[Int => TestData]= (0 to 2).map{
    _ => TestData("something",_)
  }

For scenario 2

case class TestData(name : String , idNumber : Int)
val createRandomData: immutable.Seq[TestData] = (0 to 2).map{
    i => TestData("something",i)
  }

Why in scenario 1 is return type is a function not a collection of Seq.

whoisthis
  • 33
  • 8

2 Answers2

3

Because TestData("something",i) has type TestData and TestData("something",_) has type Int => TestData.

The second underscore is used for lambda (while the first underscore means that argument doesn't matter).

What are all the uses of an underscore in Scala?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
3

When you do something like this:

    case class TestData(name : String , idNumber : Int)
    val createRandomData : immutable.IndexedSeq[Int => TestData]= (0 to 2).map{
        _ => TestData("something",_)
    }

the first underscore means that you ignore the value of the parameter, then you use another underscore in the body of the function passed to map so you are creation a lambda function that ends to be the return type.

What you wanted to in in first scenario was:

case class TestData(name : String , idNumber : Int)
val createRandomData = (0 to 2).map{
  TestData("something",_)
}

Which has TestData as return type.