HiveBrain v1.2.0
Get Started
← Back to all entries
snippetModerate

Implement the method "plus"

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
plustheimplementmethod

Problem

I'm implementing a plus method that should work this way:

1 plus 2      // 3
"a" plus "b"  // "a and b = ab"


Here is my implementation:

object MyMath {
  implicit class MyMath(a: Any) {
    def plus(b: Any) = {
      (a, b) match {
        case (s: String, s2: String) => s"$s and $s2"
        case(i: Int, i2: Int) => i + i2
      }
    }
  }

  def main(args: Array[String]) {
    println(1 plus 2)
    println("a" plus "b")
  }
}


Should I avoid using type Any? Is this a sign of a code smell if I use Any too much?

Solution

First off: Apologies for the shortness of this review. There's not much code, after all.

You've got a bit of inconsistent style with whitespace after your cases -- I haven't done Scala in a while, but if I'm remembering right, you're supposed to have a space after.

I'd recommend renaming i and s to i1 and s1, respectively, just to be consistent.

Your 'spec' says that "a" plus "b" should return "a and b = ab", but it actually returns "a and b". Personally, I think it should return "ab", a la string concatenation.

Using Any is not a code smell, though some error throwing may be in order if any types other than Int or String are used, so that if I call 1.0 plus "a", I don't just get nothing. It's up to you which type to use, though personally I'd use an IllegalArgumentException.

Aside from that, it looks good! Well done.

Context

StackExchange Code Review Q#94823, answer score: 10

Revisions (0)

No revisions yet.