How to pass an object to a method in Scala

后端 未结 4 648
清酒与你
清酒与你 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:08

    In addition to Jörg W Mittag's answer, you can create an interface:

    trait IConstants {
      def constantA: Double
    }
    
    object Constants extends IConstants {
      val constantA: Double = ???
    }
    
    def calc(numbers:Seq[Double], constants: IConstants) = ???
    

    Whether this is useful very much depends on your specific situation.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 22:32

    Look at the synthax of your method definition: what does your calc method produce ? Unit ? Int ? I suggest that you review the basics of the Scala synthax first

    0 讨论(0)
  • 2021-01-18 22:33

    You can use the Any type

    def calc(numbers:Seq[Double], constants: Any) 
    

    but this wouldn't allow you to access the constantA value. Alternatively you could define a trait with the constant and let you object implement that:

    trait ConstantA {
      val constantA:Double
    }
    
    object Constant extends ConstantA {
      override val constantA:Double = 0.0
    }
    
    def calc(numbers:Seq[Double], constants: ConstantA) {
       ...
       // use constants.constantA
       println(constants.constantA)
       ...
    }
    
    0 讨论(0)
提交回复
热议问题