0

Is there a better way to rewrite these overloaded methods to avoid the double definition issue?

def test(a: Option[Int]) {
  println(a)
}

def test(a: Option[String]) {
  println(a)
}

test(Some(1))

test(Some("1"))

Example -> https://scastie.scala-lang.org/3V57pKeATFSmMNnDV2xBxA

glarkou
  • 7,023
  • 12
  • 68
  • 118
  • 2
    It depends, on what you want to do. Maybe you can just use a generic, or a **typeclass**. – Luis Miguel Mejía Suárez Dec 09 '21 at 15:09
  • @LuisMiguelMejíaSuárez I do not want to have functions with different names that do exactly the same thing with different parameters. I understand why the `Option` would not work but is there a cleaner way to write it? instead of just changing the name of the function? – glarkou Dec 09 '21 at 15:17
  • 1
    you can get couple of answers in this post : https://stackoverflow.com/questions/3307427/scala-double-definition-2-methods-have-the-same-type-erasure – Nikunj Kakadiya Dec 09 '21 at 15:55
  • Does this answer your question? [Scala double definition (2 methods have the same type erasure)](https://stackoverflow.com/questions/3307427/scala-double-definition-2-methods-have-the-same-type-erasure) – Nikunj Kakadiya Dec 09 '21 at 15:55
  • @glarkou _"I do not want to have functions with different names that do exactly the same thing with different parameters"_ I get that, I am asking what are you doing in those methods. Because it seems a simple `def test[A](a: Option[A]): Unit = {` may work, but not sure if that is enough for your real code or not. – Luis Miguel Mejía Suárez Dec 09 '21 at 16:00

1 Answers1

5

Use a polymorphic method:

def test[T](a: Option[T]): Unit = {
    println(a)
  }
  
test(Some(1))
test(Some("1"))
gatear
  • 946
  • 2
  • 10