gpt4 book ai didi

scala - 是否可以将不同特征的方法链接起来?

转载 作者:行者123 更新时间:2023-12-04 13:54:17 26 4
gpt4 key购买 nike

我有以下代码:

class Parameterizable{
var map: Map[String, String] = new scala.collection.immutable.HashMap()
def put(entry: Tuple2[String, String]) = {
map = map + entry; this
}
}

class Query() extends Parameterizable{
override def toString = {
map.isEmpty match{
case true => ""
case false => "?" + map.map{case (key, value) => key + "=" + value}.mkString("&")
}
}
}

trait PageParameter extends Parameterizable{
def page(page: Int) = put(("page" -> page.toString))
def pageSize(pageSize: Int) = put(("pagesize" -> pageSize.toString))
}

trait DateParameter extends Parameterizable{
def fromDate(date: java.util.Date) = put(("fromdate" -> (date.getTime()/1000L).toString()))
def toDate(date: java.util.Date) = put(("todate" -> (date.getTime()/1000L).toString()))
}
//and other similar traits

我想做类似的事情:
class ExtendedQuery extends Query with PageParameter with DateParameter
val query = new ExtendedQuery
query.page(4).pageSize(5).fromDate(new java.util.Date)

或者:
query.and().page(4).and().pageSize(5).and().fromDate(new java.util.Date)

Scala有可能吗?

最佳答案

您可以将这些方法声明为返回this.type,然后从它们中返回this:

trait PageParameter extends Parameterizable{
def page(page: Int) : this.type = { put(("page" -> page.toString)); this }
def pageSize(pageSize: Int): this.type = { put(("pagesize" -> pageSize.toString)); this }
}

然后,您可以在使用站点上根据需要链接调用。请参阅以下示例:
scala> trait Wibble {
| def foo : this.type = { println("foo"); this }
| }
defined trait Wibble

scala> trait Wobble extends Wibble {
| def bar: this.type = { println("bar"); this }
| }
defined trait Wobble

scala> trait Wubble extends Wibble {
| def baz: this.type = { println("baz"); this }
| }
defined trait Wubble

现在我可以测试了
scala> new Wibble with Wobble with Wubble
res0: java.lang.Object with Wibble with Wobble with Wubble = $anon$1@937e20

scala> res0.bar.baz.foo
bar
baz
foo
res1: res0.type = $anon$1@937e20

关于scala - 是否可以将不同特征的方法链接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6955563/

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