Search code examples
scalatype-annotation

Why the type annotation is changing in Scala for one val


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.


Solution

  • 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.