Override “operators” and println method in Scala











up vote
0
down vote

favorite












I need to create methods for basic operations for different types so the output of the expression: println(1 + 2*I + I*3 + 2) is 3+5i. I am new to Scala and here is what I have so far:



class IClass() {

var value = 0
def *(number: Int): String = {
//value += number
value + "i"
}

}

object ComplexNumbers {

var TotalValue: Int = 0
var TotalString: String = ""
// ...

def Complex(num1: Int, num2: Int): String ={
num1 + "+" + num2 + "i"
}

implicit class IntMultiply(private val a: Int) extends AnyVal {

def + (b: String)= {
if(b.contains("i")){
TotalValue += a
TotalString.concat(b)
}
}

def * (b: IClass) = {
//b.value += a
a + "i"
}
}

implicit class StringAdd(private val a: String) extends AnyVal {
def + (b: String): String = {
if(b.contains("i")){

}
a + "i"
}
}

def main(args: Array[String]) {

println(Complex(1,2)) // 1+2i

val I = new IClass()
println(1 + 2*I + I*3 + 2) // 3+5i

// val c = (2+3*I + 1 + 4*I) * I
// println(-c) // 7-3i
}
}


I think I am going in a wrong direction with this because by implementing these operation methods on types I get an error in the println: Type Mismach because of the Any return type where I only update fields without returning anything. Any idea how to implement this?










share|improve this question


























    up vote
    0
    down vote

    favorite












    I need to create methods for basic operations for different types so the output of the expression: println(1 + 2*I + I*3 + 2) is 3+5i. I am new to Scala and here is what I have so far:



    class IClass() {

    var value = 0
    def *(number: Int): String = {
    //value += number
    value + "i"
    }

    }

    object ComplexNumbers {

    var TotalValue: Int = 0
    var TotalString: String = ""
    // ...

    def Complex(num1: Int, num2: Int): String ={
    num1 + "+" + num2 + "i"
    }

    implicit class IntMultiply(private val a: Int) extends AnyVal {

    def + (b: String)= {
    if(b.contains("i")){
    TotalValue += a
    TotalString.concat(b)
    }
    }

    def * (b: IClass) = {
    //b.value += a
    a + "i"
    }
    }

    implicit class StringAdd(private val a: String) extends AnyVal {
    def + (b: String): String = {
    if(b.contains("i")){

    }
    a + "i"
    }
    }

    def main(args: Array[String]) {

    println(Complex(1,2)) // 1+2i

    val I = new IClass()
    println(1 + 2*I + I*3 + 2) // 3+5i

    // val c = (2+3*I + 1 + 4*I) * I
    // println(-c) // 7-3i
    }
    }


    I think I am going in a wrong direction with this because by implementing these operation methods on types I get an error in the println: Type Mismach because of the Any return type where I only update fields without returning anything. Any idea how to implement this?










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I need to create methods for basic operations for different types so the output of the expression: println(1 + 2*I + I*3 + 2) is 3+5i. I am new to Scala and here is what I have so far:



      class IClass() {

      var value = 0
      def *(number: Int): String = {
      //value += number
      value + "i"
      }

      }

      object ComplexNumbers {

      var TotalValue: Int = 0
      var TotalString: String = ""
      // ...

      def Complex(num1: Int, num2: Int): String ={
      num1 + "+" + num2 + "i"
      }

      implicit class IntMultiply(private val a: Int) extends AnyVal {

      def + (b: String)= {
      if(b.contains("i")){
      TotalValue += a
      TotalString.concat(b)
      }
      }

      def * (b: IClass) = {
      //b.value += a
      a + "i"
      }
      }

      implicit class StringAdd(private val a: String) extends AnyVal {
      def + (b: String): String = {
      if(b.contains("i")){

      }
      a + "i"
      }
      }

      def main(args: Array[String]) {

      println(Complex(1,2)) // 1+2i

      val I = new IClass()
      println(1 + 2*I + I*3 + 2) // 3+5i

      // val c = (2+3*I + 1 + 4*I) * I
      // println(-c) // 7-3i
      }
      }


      I think I am going in a wrong direction with this because by implementing these operation methods on types I get an error in the println: Type Mismach because of the Any return type where I only update fields without returning anything. Any idea how to implement this?










      share|improve this question













      I need to create methods for basic operations for different types so the output of the expression: println(1 + 2*I + I*3 + 2) is 3+5i. I am new to Scala and here is what I have so far:



      class IClass() {

      var value = 0
      def *(number: Int): String = {
      //value += number
      value + "i"
      }

      }

      object ComplexNumbers {

      var TotalValue: Int = 0
      var TotalString: String = ""
      // ...

      def Complex(num1: Int, num2: Int): String ={
      num1 + "+" + num2 + "i"
      }

      implicit class IntMultiply(private val a: Int) extends AnyVal {

      def + (b: String)= {
      if(b.contains("i")){
      TotalValue += a
      TotalString.concat(b)
      }
      }

      def * (b: IClass) = {
      //b.value += a
      a + "i"
      }
      }

      implicit class StringAdd(private val a: String) extends AnyVal {
      def + (b: String): String = {
      if(b.contains("i")){

      }
      a + "i"
      }
      }

      def main(args: Array[String]) {

      println(Complex(1,2)) // 1+2i

      val I = new IClass()
      println(1 + 2*I + I*3 + 2) // 3+5i

      // val c = (2+3*I + 1 + 4*I) * I
      // println(-c) // 7-3i
      }
      }


      I think I am going in a wrong direction with this because by implementing these operation methods on types I get an error in the println: Type Mismach because of the Any return type where I only update fields without returning anything. Any idea how to implement this?







      scala operators






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 4 at 10:02









      Harun Cerim

      7071619




      7071619
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          3
          down vote



          accepted










          You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.



          case class ComplexInt(real: Int, im: Int) {
          def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
          def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im,
          real * other.im + im * other.real
          )
          def unary_- = ComplexInt(-real, -im)
          def -(other: ComplexInt) = this + -other

          override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
          case 0 => ""
          case 1 if real == 0 => "i"
          case 1 => " + i"
          case n if n < 0 || real == 0 => s"${n}i"
          case n => s"+${n}i"
          })
          }

          object ComplexInt {
          val I = ComplexInt(0, 1)
          implicit def fromInt(n: Int) = ComplexInt(n, 0)
          }


          Now, you just need to import ComplexInt.I,
          and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.



          You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).






          share|improve this answer























          • As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
            – Harun Cerim
            2 days ago






          • 1




            pretty gnarly stuff for a first assignment
            – Seth Tisue
            2 days ago











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53139608%2foverride-operators-and-println-method-in-scala%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote



          accepted










          You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.



          case class ComplexInt(real: Int, im: Int) {
          def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
          def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im,
          real * other.im + im * other.real
          )
          def unary_- = ComplexInt(-real, -im)
          def -(other: ComplexInt) = this + -other

          override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
          case 0 => ""
          case 1 if real == 0 => "i"
          case 1 => " + i"
          case n if n < 0 || real == 0 => s"${n}i"
          case n => s"+${n}i"
          })
          }

          object ComplexInt {
          val I = ComplexInt(0, 1)
          implicit def fromInt(n: Int) = ComplexInt(n, 0)
          }


          Now, you just need to import ComplexInt.I,
          and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.



          You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).






          share|improve this answer























          • As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
            – Harun Cerim
            2 days ago






          • 1




            pretty gnarly stuff for a first assignment
            – Seth Tisue
            2 days ago















          up vote
          3
          down vote



          accepted










          You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.



          case class ComplexInt(real: Int, im: Int) {
          def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
          def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im,
          real * other.im + im * other.real
          )
          def unary_- = ComplexInt(-real, -im)
          def -(other: ComplexInt) = this + -other

          override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
          case 0 => ""
          case 1 if real == 0 => "i"
          case 1 => " + i"
          case n if n < 0 || real == 0 => s"${n}i"
          case n => s"+${n}i"
          })
          }

          object ComplexInt {
          val I = ComplexInt(0, 1)
          implicit def fromInt(n: Int) = ComplexInt(n, 0)
          }


          Now, you just need to import ComplexInt.I,
          and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.



          You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).






          share|improve this answer























          • As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
            – Harun Cerim
            2 days ago






          • 1




            pretty gnarly stuff for a first assignment
            – Seth Tisue
            2 days ago













          up vote
          3
          down vote



          accepted







          up vote
          3
          down vote



          accepted






          You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.



          case class ComplexInt(real: Int, im: Int) {
          def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
          def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im,
          real * other.im + im * other.real
          )
          def unary_- = ComplexInt(-real, -im)
          def -(other: ComplexInt) = this + -other

          override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
          case 0 => ""
          case 1 if real == 0 => "i"
          case 1 => " + i"
          case n if n < 0 || real == 0 => s"${n}i"
          case n => s"+${n}i"
          })
          }

          object ComplexInt {
          val I = ComplexInt(0, 1)
          implicit def fromInt(n: Int) = ComplexInt(n, 0)
          }


          Now, you just need to import ComplexInt.I,
          and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.



          You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).






          share|improve this answer














          You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.



          case class ComplexInt(real: Int, im: Int) {
          def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
          def * (other: ComplexInt) = ComplexInt(
          real * other.real - im * other.im,
          real * other.im + im * other.real
          )
          def unary_- = ComplexInt(-real, -im)
          def -(other: ComplexInt) = this + -other

          override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
          case 0 => ""
          case 1 if real == 0 => "i"
          case 1 => " + i"
          case n if n < 0 || real == 0 => s"${n}i"
          case n => s"+${n}i"
          })
          }

          object ComplexInt {
          val I = ComplexInt(0, 1)
          implicit def fromInt(n: Int) = ComplexInt(n, 0)
          }


          Now, you just need to import ComplexInt.I,
          and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.



          You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered 2 days ago









          Dima

          22.9k32134




          22.9k32134












          • As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
            – Harun Cerim
            2 days ago






          • 1




            pretty gnarly stuff for a first assignment
            – Seth Tisue
            2 days ago


















          • As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
            – Harun Cerim
            2 days ago






          • 1




            pretty gnarly stuff for a first assignment
            – Seth Tisue
            2 days ago
















          As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
          – Harun Cerim
          2 days ago




          As I said, I just started learning Scala and this was my first assignment. I knew I shouldn't narrow the solution to only one scenario but I thought it would be somehow easier to get the answer. This is actually pretty amazing what you did. Thank you very much.
          – Harun Cerim
          2 days ago




          1




          1




          pretty gnarly stuff for a first assignment
          – Seth Tisue
          2 days ago




          pretty gnarly stuff for a first assignment
          – Seth Tisue
          2 days ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53139608%2foverride-operators-and-println-method-in-scala%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          這個網誌中的熱門文章

          Xamarin.form Move up view when keyboard appear

          Post-Redirect-Get with Spring WebFlux and Thymeleaf

          Anylogic : not able to use stopDelay()