Is there a way to migrate a 0-arity method having parentheses to not having parentheses?

Viewed 58

Say I designed some API and shortsightedly gave a 0-arity function parentheses in its definition

class Foo(value: String) {
  def chars(): Seq[Char] = value.toSeq
}

This means you obnoxiously have to provide empty parentheses if you want to follow a call to this method with an apply on the returned Seq:

val f = new Foo("Hello")
println(f.chars()(3))

This is obviously not ideal, it would be better to be able to write:

println(f.chars(3))

Of course, if you remove the parentheses from the method definition, it breaks all existing uses that do provide parentheses. Is there a way to migrate a 0-arity function from having parentheses to not having them without breaking all of the uses?

1 Answers

You could give the parened method an unused vararg.

class Foo(value: String) {
  def chars(cs:Char*): Seq[Char] = value.toSeq
  def chars: Seq[Char] = value.toSeq
}

(new Foo("wxyz")).chars()(2)  //res0: Char = y
(new Foo("wxyz")).chars(2)    //res1: Char = y
Related