Madaray
Madaray

Reputation: 105

declare val with a loop in scala

Im learning scala and Im wondering if it's possible to declare a val in the following way :

val aLotOfZero : String = for(i<-0 to 63) {"0"}

instead of

  var tmp : String = ""
  for(i<-0 to 63)
    {
      tmp += "0"
    }
  val aLotOfZero : String = tmp 

And if it's possible to replace the "0" by other stuff.

Thanks you

Upvotes: 0

Views: 554

Answers (1)

nicodp
nicodp

Reputation: 2392

If what you want is to build a String value with n zeroes, you could use a for yielding the character 0 and then making the returning Vectorto a string using mkString as follows:

scala> val aLotOfZeroes: String = (for (i <- 0 to 63) yield "0").mkString
aLotOfZeroes: String = 0000000000000000000000000000000000000000000000000000000000000000

And then, you could generalize it by adding a parameter likewise:

scala> def aLotOfZeroes(n: Int): String = (for (i <- 0 to n) yield "0").mkString 
aLotOfZeroes: (n: Int)String

scala> aLotOfZeroes(10)
res2: String = 00000000000

scala> val zeroes: String = aLotOfZeroes(10)
zeroes: String = 00000000000

scala> zeroes
res3: String = 00000000000

Also, from @dividebyzero's comment, you can use *:

scala> "0" * 64
res13: String = 0000000000000000000000000000000000000000000000000000000000000000

And define:

scala> def aLotOfZeroes: Int => String = "0" * _
aLotOfZeroes: Int => String

scala> aLotOfZeroes(10)
res16: String = 0000000000

Upvotes: 2

Related Questions