特征的直接继承失败,但代理有效

时间:2015-10-22 16:12:54

标签: scala

为什么添加代理特征工作和直接继承失败?

I've created a runnable project over on github

如果你克隆了回购并运行sbt console后跟com.stackoverflow.question.main.Question.main(Array.empty[String]),你应该得到输出结果:

this-is-the-host-name
java.lang.NullPointerException
  at net.ceedubs.ficus.FicusConfig$class.as(FicusConfig.scala:9)
  at net.ceedubs.ficus.SimpleFicusConfig.as(FicusConfig.scala:16)
  at com.stackoverflow.question.AppConfig$class.conn(Config.scala:12)
  at com.stackoverflow.question.main.BadDatabaseService$.conn(package.scala:12)
  at com.stackoverflow.module.HostConnector$class.getHost(Database.scala:25)
  at com.stackoverflow.question.main.BadDatabaseService$.getHost(package.scala:12)
  at com.stackoverflow.module.DatabaseConnector$class.$init$(Database.scala:18)
  at com.stackoverflow.question.main.BadDatabaseService$.<init>(package.scala:12)
  at com.stackoverflow.question.main.BadDatabaseService$.<clinit>(package.scala)
  at com.stackoverflow.question.main.Question$.main(App.scala:8)
  ... 43 elided

第一行this-is-the-host-name是从包对象DatabaseService生成的,而NullPointerException是由BadDatabaseService包对象生成的。两者都是相同的,除了DatabaseService继承自代理特征,而BadDatabaseService直接从特征继承。相关代码在这里是为了方便起见,也可以在github repo中看到。

package.scala:

package com.stackoverflow.question

import com.stackoverflow.module._
import com.stackoverflow.question.AppConfig

package main {
  trait DataConfig extends ModuleConfig {
    def conn = AppConfig.conn
  }

  object DatabaseService extends TableFunctions with HostConnector with DataConfig   // This works with the proxy
  object BadDatabaseService extends TableFunctions with HostConnector with AppConfig // This fails with NullPointerException, it's the ConfigFactory.load that returns null
}

Config.scala:

package com.stackoverflow.question

import com.stackoverflow.module.{ ModuleConfig, ModuleConfiguration }
import com.typesafe.config.{ Config, ConfigFactory }
import net.ceedubs.ficus.Ficus._

object AppConfig extends AppConfig

trait AppConfig extends ModuleConfig {

  def config: Config = ConfigFactory.load()
  def conn = config.as[ModuleConfiguration]("stackoverflow.conn")

  val name = config.as[String]("stackoverflow.name")
}

请帮助我理解为什么我无法直接从AppConfig继承,为什么ConfigFactory.load在继承AppConfig时返回null,而在redirect()->back()为共同对象时返回null通过代理继续调用。

1 个答案:

答案 0 :(得分:1)

另一个不适用于关联问题的解决方案是AppConfig.namelazy val