65

I would like to do the following more efficiently:

def repeatChar(char:Char, n: Int) = List.fill(n)(char).mkString
def repeatString(char:String, n: Int) = List.fill(n)(char).mkString

repeatChar('a',3)     // res0: String = aaa
repeatString("abc",3) // res0: String = abcabcabc
TimY
  • 5,256
  • 5
  • 44
  • 57

2 Answers2

131

For strings you can just write "abc" * 3, which works via StringOps and uses a StringBuffer behind the scenes.

For characters I think your solution is pretty reasonable, although char.toString * n is arguably clearer. Do you have any reason to suspect the List.fill version isn't efficient enough for your needs? You could write your own method that would use a StringBuffer (similar to * on StringOps), but I would suggest aiming for clarity first and then worrying about efficiency only when you have concrete evidence that that's an issue in your program.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • 3
    Thank you Travis. This was more out of academic interest and, as you suggested, to improve clarity if possible, rather than a need to improve performance. I just wanted to make sure I'm picking up the best practices from the beginning. – TimY Jul 26 '15 at 14:14
  • @TimY That makes sense—I wish more people would use "efficiency" in contexts other than performance! – Travis Brown Jul 26 '15 at 14:19
  • Not sure how being reasonable has been determined here: does this answer rely on any benchmark against other options, such as manipulating plain Java strings or anything else, or did you rather mean this is the idiomatic way in scala? – matanster Oct 16 '15 at 19:29
  • @TravisBrown What if n is Long? What this solution will work? – Moustafa Mahmoud Jul 19 '19 at 17:59
  • 2
    @MoustafaMahmoud Why not try it? – Travis Brown Jul 20 '19 at 07:35
  • 1
    You can always call `toInt` on a `Long` (which will overflow if the `Long` is too large, but that seems unlikely to be a meaningful case here, anyway). – Travis Brown Jul 21 '19 at 09:37
0

you can simply define:

def repeatChar(char:Char, n: Int) = char.toString() * n
def repeatString(char:String, n: Int) = char * n
Pallav
  • 332
  • 3
  • 8