gpt4 book ai didi

scala - 具有依赖特征和依赖实现的设计问题

转载 作者:行者123 更新时间:2023-12-02 05:26:03 25 4
gpt4 key购买 nike

我有以下设计问题:

/**
* Those 2 traits are the public API
*/
trait Box {
def include(t: Token): Box
}
trait Token

/**
* Implementation classes
*/
case class BoxImpl(id: Int) extends Box {
/**
* the implementation of this method depends on the implementation
* of the Token trait
* TODO: REMOVE asInstanceOf
*/
def include(t: Token) = BoxImpl(t.asInstanceOf[TokenImpl].id + id)
}
case class TokenImpl(id: Int) extends Token

// use case
val b: Box = new BoxImpl(3)
val o: Token = new TokenImpl(4)

// == BoxImpl(7)
b.include(o)

在上面的代码中,我不想在公共(public) API 中公开 id(甚至不将其设置为 private[myproject],因为那样仍会包含循环我项目中的依赖项)。

有什么方法可以让公共(public) API 完好无损,同时让实现类彼此具有一定的可见性(没有丑陋的转换)?

最佳答案

输入参数或成员:

trait Box {
type T <: Token
def include(t: T): Box
//def include(t: Token): Box
}
trait Token

case class BoxImpl(id: Int) extends Box {
type T = TokenImpl
def include(t: T) = BoxImpl(t.id + id)

/*
def include(t: Token) = t match {
case ti: TokenImpl => BoxImpl(ti.id + id)
case _ => throw new UnsupportedOperationException
}
*/

//def include(t: Token) = BoxImpl(t.asInstanceOf[TokenImpl].id + id)
}
case class TokenImpl(id: Int) extends Token

切片和切 block 的方法有很多种,因此才有了蛋糕图案,众所周知的一 block 蛋糕:

trait Boxer {
type Token <: Tokenable
trait Box {
def include(t: Token): Box
}
trait Tokenable
}

trait Boxed extends Boxer {
type Token = TokenImpl
case class BoxImpl(id: Int) extends Box {
override def include(t: Token) = BoxImpl(t.id + id)
}
case class TokenImpl(id: Int) extends Tokenable
}

trait User { this: Boxer =>
def use(b: Box, t: Token): Box = b.include(t)
}

object Test extends App with Boxed with User {
val b: Box = new BoxImpl(3)
val o: Token = new TokenImpl(4)
println(use(b, o))
}

关于scala - 具有依赖特征和依赖实现的设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com