Documentation pattern - secondary constructors

未关闭
#61 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
42/100
Issue 类型
文档
描述清晰度
基本清楚
活跃度
停滞
技术栈
scala
领域
documentation

调研方向

未指定文档文件或测试。首先定位 macwire 中关于构造函数的文档入口,然后纳入 issue 中展示的次构造函数、Defaults 和工厂模式。完成的标准是:该模式已记录在适当的指南中,并且示例在周围的文档中易于理解。

由索引模型根据 Issue 内容生成。

描述

If you're wondering how to deal with multiple constructors with macwire here is a pattern.

So you have this X class that provides default implementations for some of its parameters:

class X(a: A, b: B, c: C, d: D) {
  // secondary constructor, providing defaults for C and D
  def this(a: A, b: B) = {
    this(a, b, new DefaultC, new DefaultD)
  }
}

This can also be written using default parameters (as long as DefaultC or DefaultD does not depend on a or b), but down the line that's the same:

// default parameters, which will be turned into secondary constructors
class X(a: A, b: B, c: C = new DefaultC, d: D = new DefaultD)

(Un)fortunately macwire only looks at the primary constructor (BTW something could be said in the documentation about why this is better).
To workaround that "limitation" here is an alternative:

class X(a: A, b: B, c: C, d: D) {
  // no secondary constructor
}

object X {
    import Defaults._

    def apply(a: A, b: B) : X = wire[X]

    trait Defaults {
       lazy val c = wire[DefaultC]
       lazy val d = wire[DefaultD]
    }
    object Defaults extends Defaults   
}

We can now re-use the defaults provided by X if we're interested in them:

class MyModule extends X.Defaults {
   lazy val a: A = wire[AImpl]
   lazy val b: B = wire[BImpl]
   lazy val x: X = wire[X]
}

Things can get a little more tricky if DefaultC needs some parameters that we're unable to provide. In that case we'll resort to factories:

object X {
    import Defaults._

    def apply(a: A, b: B, cDep: CDep) : X = { 
       val c = buildC(cDep)
       wire[X]
   }

    trait Defaults {
       def buildC(cDep: CDep) = wire[DefaultC]
       lazy val d = wire[DefaultD]
    }
    object Defaults extends Defaults   
}

And in your module

class MyModule extends X.Defaults {
   lazy val a: A = wire[AImpl]
   lazy val b: B = wire[BImpl]
   lazy val cDep: CDep = wire[CDepImpl]
   lazy val c: C = buildC(cDep)
   lazy val x: X = wire[X]
}
主要语言
Scala
星标
1.3k
派生
77
平均合并
9 分钟
30 天内合并 PR
4

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

softwaremill/macwire 的其他 Issue

查看 softwaremill/macwire 的全部 Issue

相似的 Issue

更多 Scala Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。