如何将对象传递给 Scala 中的方法

2023-11-25

如何将对象的引用传递给 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

当然我也只能参考一下Constants不通过参数列表传递它,但我更愿意将方法的所有依赖项显式地作为参数传递。


Constants是一个对象。您不指定对象作为方法参数的参数类型,而是指定types作为方法参数的参数类型:

def calc(numbers:Seq[Double], constants: Constants.type) = ???

一般来说,更精确的类型是好的,但在这种情况下,使用过于精确类型,因为该类型只有一个实例Constants.type,所以除了Constants对象作为参数,这使得“参数化”的整个想法变得毫无意义。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将对象传递给 Scala 中的方法 的相关文章

随机推荐