Home > database >  Overloaded methods with optional parameters
Overloaded methods with optional parameters

Time:12-10

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

CodePudding user response:

Use a polymorphic method:

def test[T](a: Option[T]): Unit = {
    println(a)
  }
  
test(Some(1))
test(Some("1"))
  • Related