0

I am new to Scala. I was trying to create functions like +, * in one of the class. Below is the class and its definition -

case class StringWrapper2(str : String){
  def +(x:Int) : String ={
    println(s"x: $x, str :$str")
    str.concat(x.toString);
  }
  def *(x:Int) : String = {
    println(s"x: $x, str :$str")
    str.repeat(x);
  }
}

I created instance and called above function -

val sw: StringWrapper2 = new StringWrapper2("ABC")
val result = sw + 10 * 2

I am expecting the result - ABC10ABC10 But I am getting result as ABC20

Also the println statements that I added in method are not printed. It means these symbolic methods are not getting called and some different implementation (probably String class) is getting called.

Any idea why this might be happening and how to resolve this issue?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30
  • 2
    It's because of the order of the operators. Try to do `(sw + 10)* 2`. But Just for you know `String` has + and `StringOps` has `*` See [Efficiently repeat a character/string n times in Scala](https://stackoverflow.com/a/31637882/2359227) – Tomer Shetah Dec 23 '20 at 06:38
  • 1
    Rahul, will you accept my answer? – Tomer Shetah Feb 04 '21 at 20:02

1 Answers1

3

According to Operator precedence in Scala, * is calculated before +. For example 2 + 2 * 2 will result in 6, and not 8.

In your example, 10 * 2 is calculated before, resulting in 20, and then when you add sw + 20 you get ABC20.

To your second question. Please note that in your example the println from the + method is printed. The reason the second line isn't printed, is that you return a String, instead of StringWrapper. To get what you want, you need to do something like:

case class StringWrapper2(str : String){
  def +(x:Int) : StringWrapper2 ={
    println(s"x: $x, str :$str")
    StringWrapper2(str.concat(x.toString))
  }
  def *(x:Int) : StringWrapper2 = {
    println(s"x: $x, str :$str")
    StringWrapper2(str * x)
  }
}

val sw: StringWrapper2 = new StringWrapper2("ABC")
val result = (sw + 10) * 2

Code run at Scastie.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35