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
For strings you can just write
"abc" * 3
, which works viaStringOps
and uses aStringBuffer
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 theList.fill
version isn't efficient enough for your needs? You could write your own method that would use aStringBuffer
(similar to*
onStringOps
), 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.I know this is an old question, another solution would be what I have below
result from REPL repeatChar('a', 2) => res1: String = aa