How to pass an object to a method in Scala

后端 未结 4 649
清酒与你
清酒与你 2021-01-18 21:46

How can I pass the reference of an object to method in Scala? E.g. I want this to compile

object Constants {
  val constantA:Double = ???
}


def calc(number         


        
4条回答
  •  执念已碎
    2021-01-18 22:27

    Constants is an object. You don't specify objects as parameter types for method parameters, you specify types as parameter types for method parameters:

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

    Generally speaking, more precise types are good, but in this case, it might be overdoing it with an overly precise type, since there is exactly one instance of the type Constants.type, so you cannot ever pass anything other than the Constants object as an argument, which makes the whole idea of "parameterizing" rather pointless.

提交回复
热议问题