Rap*_*oth 4 methods singleton scala
如何将对象的引用传递给Scala中的方法?我想要这个编译
object Constants {
val constantA:Double = ???
}
def calc(numbers:Seq[Double], Constants) = ??? // does not compile
def calc(numbers:Seq[Double], constants:Constants) = ??? // does not compile
Run Code Online (Sandbox Code Playgroud)
当然我可以在Constants不通过参数列表的情况下引用它,但我更愿意列出将方法的所有依赖项显式地作为参数传递.
Jör*_*tag 12
Constants是一个对象.您没有将对象指定为方法参数的参数类型,您将类型指定为方法参数的参数类型:
def calc(numbers:Seq[Double], constants: Constants.type) = ???
Run Code Online (Sandbox Code Playgroud)
一般来说,更精确的类型是好的,但在这种情况下,它可能是过度精确的类型过度,因为只有一个类型的实例Constants.type,所以你不能传递除Constants对象之外的任何东西作为参数,使"参数化"的整个想法变得毫无意义.