1
votes

I had a scala object as below which works when i type in REPL just the vec statement it displays the vector in the REPL. But If i used the return type Vector[Int] for the method def randomNumbers it will give compilation errors why ?

val vec = for (i <- 0 to 100) yield ((r.nextInt(100 - 10) + 1) + 10)

scala.collection.immutable.IndexedSeq[Int] = Vector(38, 2.......

As far i understand Vector is proper type and IndexedSeq[Int] is trait.

Below is the def for Vector

 final class Vector[+A] extends AbstractSeq[A] with IndexedSeq[A] with GenericTraversableTemplate[A, Vector] with IndexedSeqLike[A, Vector[A]] with VectorPointer[A] with Serializable with CustomParallelizable[A, ParVector[A]] 

then why should it complain ?

object Random extends App {

  def randomNumbers: IndexedSeq[Int] = {
    val r = scala.util.Random
    val vec = for (i <- 0 to 100) yield ((r.nextInt(100 - 10) + 1) + 10)
    return vec
  }

}

Gives errors:

object Basics extends App {

  def randomNumbers: Vector[Int] = {
    val r = scala.util.Random
    println(r.nextInt * 0.1 + 0.1)
    println(r.nextFloat)
    println(r.nextDouble)
    println(r.nextInt)
    println(r.nextPrintableChar)
    val vec = for (i <- 0 to 100) yield ((r.nextInt(100 - 10) + 1) + 10)
    return vec
  }

}

type mismatch; found : scala.collection.immutable.IndexedSeq[Int] required: Vector[Int]

1

1 Answers

3
votes

A Vector can be assigned to a reference defined type of IndexedSeq (because a Vector implements the IndexedSeq trait), but an IndexedSeq cannot be assigned to a referenced defined as a type Vector, which is what you're trying to do

val vec = for (i <- 0 to 100) yield ((r.nextInt(100 - 10) + 1) + 10)
vec: scala.collection.immutable.IndexedSeq[Int] = ...

You can do an unsafe cast, ie.

vec.asInstanceOf[Vector[Int]]

To force that into a reference of Vector[Int], but the compiler can't prove that that line won't fail.