Search code examples
scalaimplicit-conversion

Best way to implement a function that accepts multiple types


Given that there's no Union in scala,

I have a three functions that accept different parameters, but are otherwise exactly the same. How would I best implement this without repeating myself like I do now?

  import scala.sys.process._

  def function1(command:String):String = {
    ...
    command.!! // scala sys process execution
  }

  def function2(command:Seq[String]):String = {
    ...
    command.!! // scala sys process execution
  }

  def function3(command:ProcessBuilder):String = {
    ...
    command.!! // scala sys process execution
  }

Solution

  • There is an implicit conversion loaded from import scala.sys.process._ that will convert from String and Seq[String] to ProcessBuilder, that is what is making possible to execute the ! in those 2 types, you can use that same implicit conversion to call function3 with any of those types

    import scala.sys.process._
    function3(Seq(""))
    function3("")
    def function3(command:ProcessBuilder):String = {
        ...
        command.!!
      }
    

    this code should compile, you dont need function1 or function2. THIS WILL NOT WORK IF import scala.sys.process._ IS NOT IN THE SCOPE OF THE function2 CALL.

    You can find the implicit definitions in the package object in scala.sys.process, if you look at it you will see that is extending ProcessImplicits which is defining the implicit conversions