Efficiently repeat a character/string n times in Scala

StringScalaCharConcatenationString Concatenation

String Problem Overview


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

String Solutions


Solution 1 - String

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.

Solution 2 - String

you can simply define:

def repeatChar(char:Char, n: Int) = char.toString() * n
def repeatString(char:String, n: Int) = char * n

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimYView Question on Stackoverflow
Solution 1 - StringTravis BrownView Answer on Stackoverflow
Solution 2 - StringPallavView Answer on Stackoverflow