在scala中调用构造函数内的函数

时间:2015-05-15 19:29:12

标签: scala constructor compiler-errors

我在类构造函数中调用一个函数但是在编译代码时我不断收到错误:找不到值:churnPeriodfnc 这是我正在运行的代码

 class CustStoryN (var custId:String,
             var rootEventType:String,
             var rootEventTime:Long,
             var eventStory:mutable.MutableList[StoryEventN]) extends Serializable {
 def this(custID: String,rootEventType: String, rootEventTim: Long, eventStory: mutable.MutableList[StoryEventN], churnPeriod: Boolean, churnMode: Boolean) 
 {
    this(custID,rootEventType,rootEventTim,
      churnPeriodfnc(churnPeriod, churnMode,eventStory))
 }

这里是编译器无法识别的ChurnPeriodFnc函数,我没有复制churn periodfunc,现在只是假设我对eventstory进行了一些更改并输出了一个新的eventstory:

    def churnPeriodfnc(churnPeriod: Boolean, churnMode: Boolean, eventStory: mutable.MutableList[StoryEventN]): mutable.MutableList[StoryEventN] = {
  eventStory  }

2 个答案:

答案 0 :(得分:1)

如果{class 1}}在班级中定义 (实例方法),或者继承;你不能在构造函数中调用它。

如果churnPeriodfnc在CustStoryN的配套对象中定义(如静态方法);您必须导入它或将其称为churnPeriodfnc

如果它在另一个对象中定义,则上述规则仍适用。

答案 1 :(得分:0)

我遇到了类似的问题,但我没有发现这种行为逻辑(我知道还没有该类的实例,并且该函数尚不存在,但是嘿,该函数存在于我尝试的类中实例化。)

要解决此问题,我建议您在这样的伴随对象中使用Apply函数:

case class Human(id: Int, name: String)

object Human {

  def apply(id: Int): Human = new Human(id, withName(id))

  def withName(id: Int): String = "Goku" /* Some behavior to get the name */

}

如果您在REPL中尝试此操作,则应具有以下行为:

scala> Human(3)
res0: Human = Human(3,Goku)