【问题标题】:Auxiliary constructor invoking what seems to be an undefined method辅助构造函数调用似乎是未定义的方法
【发布时间】:2020-06-25 07:43:18
【问题描述】:

OOP 新手。以下 scala 代码用于参数协商框架 Diplomacy。

package chipsalliance.rocketchip

object config { 
  //OP: Definition of View, Field omitted
  abstract class Parameters extends View {
    final def ++ (x: Parameters): Parameters =
      new ChainParameters(this, x)

    final def alter(f: (View, View, View) => PartialFunction[Any,Any]): Parameters =
      Parameters(f) ++ this

    final def alterPartial(f: PartialFunction[Any,Any]): Parameters =
      Parameters((_,_,_) => f) ++ this

    final def alterMap(m: Map[Any,Any]): Parameters =
      new MapParameters(m) ++ this

    protected[config] def chain[T](site: View, tail: View, pname: Field[T]): Option[T]
    protected[config] def find[T](pname: Field[T], site: View) = chain(site, new TerminalView, pname)
  }

  object Parameters {
    def empty: Parameters = new EmptyParameters
    def apply(f: (View, View, View) => PartialFunction[Any,Any]): Parameters = new PartialParameters(f)
  }

  class Config(p: Parameters) extends Parameters {
    def this(f: (View, View, View) => PartialFunction[Any,Any]) = this(Parameters(f))

    protected[config] def chain[T](site: View, tail: View, pname: Field[T]) = p.chain(site, tail, pname)
    override def toString = this.getClass.getSimpleName
    def toInstance = this
  }

  // Internal implementation:
  // OP: Some private classes omitted  
  private class PartialParameters(f: (View, View, View) => PartialFunction[Any,Any]) extends Parameters {
    protected[config] def chain[T](site: View, tail: View, pname: Field[T]) = {
      val g = f(site, this, tail)
      if (g.isDefinedAt(pname)) Some(g.apply(pname).asInstanceOf[T]) else tail.find(pname, site)
    }
  }
}

据我了解,Config 类的辅助构造函数(使用部分函数文字作为参数)调用必须返回参数对象(或类)的主构造函数(使用 Parameter 类的伴随对象的 apply 方法) ?) 通过调用 PartialParameters(f)。在我看来,受保护的方法chain只是Parameters超类中抽象链的具体实现;并且在创建/调用/调用 PartialParameters(f) 时不会被评估(因为它不是构造函数)。那么,PartialParameters(f) 在哪里求值呢?

如果我从根本上遗漏了什么,我很感激任何提示或材料链接。

【问题讨论】:

标签: scala constructor-overloading


【解决方案1】:

您的分析是正确的,所以new Config(f) 基本上是new Config(new PartialParameters(f)) 的简写。当它被评估/执行时,你有一个 Config 对象包装一个 PartialParameters 对象,但参数的 chain 方法不会被其构造函数调用。

Scala 中的语句/表达式默认是急切执行/评估的,就像在任何其他命令式语言中一样。然而,在 Scala 中,您也可以实现惰性求值。对于该函数参数,必须通过在其类型前添加 => 来显式标记为 by name

我不清楚你所说的“未定义方法”。如果您可以澄清,请编辑您的问题。

【讨论】:

  • 感谢您的回复。 “当它被评估/执行时,......”——它在哪里被评估?
  • 请查看我更新的答案。这能回答你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2011-06-28
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 2011-11-19
  • 1970-01-01
相关资源
最近更新 更多