0

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

Madaray
  • 85
  • 1
  • 9
  • 1
    What do you want to achieve? Do you want to build a string with `n` `0`s? – nicodp Dec 31 '17 at 22:15
  • 1
    Apart from adding a `yield` to your `for`, you can also use `Stream.fill(64)('0')`, both also requiring a `.mkString`. You can also use simply `"0" * 64`. Check out this very similar question. https://stackoverflow.com/questions/31637100/efficiently-repeat-a-character-string-n-times-in-scala – dividebyzero Dec 31 '17 at 22:29
  • In this case, i wanted to generate a 64 bit word then append it to a message (md5 algorithm) – Madaray Jan 01 '18 at 11:55

1 Answers1

2

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
nicodp
  • 2,362
  • 1
  • 11
  • 20