Why does the Scala compiler disallow overloaded methods with default arguments?

后端 未结 7 1795
失恋的感觉
失恋的感觉 2020-11-29 19:26

While there might be valid cases where such method overloadings could become ambiguous, why does the compiler disallow code which is neither ambiguous at compile time nor at

7条回答
  •  自闭症患者
    2020-11-29 19:47

    I'd like to cite Lukas Rytz (from here):

    The reason is that we wanted a deterministic naming-scheme for the generated methods which return default arguments. If you write

    def f(a: Int = 1)

    the compiler generates

    def f$default$1 = 1

    If you have two overloads with defaults on the same parameter position, we would need a different naming scheme. But we want to keep the generated byte-code stable over multiple compiler runs.

    A solution for future Scala version could be to incorporate type names of the non-default arguments (those at the beginning of a method, which disambiguate overloaded versions) into the naming schema, e.g. in this case:

    def foo(a: String)(b: Int = 42) = a + b
    def foo(a: Int)   (b: Int = 42) = a + b
    

    it would be something like:

    def foo$String$default$2 = 42
    def foo$Int$default$2 = 42
    

    Someone willing to write a SIP proposal?

提交回复
热议问题