问题描述
以下是Scala中类型安全,流畅的构建器模式,如 http://www.tikalk.com/java/blog/type-safe-builder-scala-using-type-constraints .它类似于 Scala和Java的构建器库,但专门处理compile-时间生成器检查.如何从Java调用它?在给定"scala.Predef $$ eq $ colon $ eq"参数的情况下,可以使用Scala AND Java的干净API来完成此操作吗?
Below is a type-safe, fluid, builder pattern in Scala as described at http://www.tikalk.com/java/blog/type-safe-builder-scala-using-type-constraints. It's similar to Builder Library for Scala and Java, but deals specifically with compile-time builder checks. How can this called from Java? Can it be done with a clean API for Scala AND Java given the "scala.Predef$$eq$colon$eq" parameters?
sealed trait TBoolean
sealed trait TTrue extends TBoolean
sealed trait TFalse extends TBoolean
class Builder[HasProperty <: TBoolean] private(i: Int) {
protected def this() = this(-1)
def withProperty(i: Int)(implicit ev: HasProperty =:= TFalse) = new Builder[TTrue](i)
def build(implicit ev: HasProperty =:= TTrue) = println(i)
}
//javap output
public class Builder extends java.lang.Object implements scala.ScalaObject{
public Builder withProperty(int, scala.Predef$$eq$colon$eq); //How is this called from Java?
public void build(scala.Predef$$eq$colon$eq);
public Builder();
}
object Builder {
def apply() = new Builder[TFalse]
}
推荐答案
与Scala版本相比,您应该能够从Java使用此API,并且会有一些额外的噪音.一些方便的字段将使事情变得安静:
You should be able to use this API from Java, with some extra noise compared to the Scala version. A few convenience fields will quiet things a bit:
object Builder {
def apply() = new Builder[TFalse]
val unassigned = =:=.tpEquals[TFalse]
val assigned = =:=.tpEquals[TTrue]
}
Java客户端代码应该最终看起来像
The Java client code should end up looking like
Builder$.MODULE$.apply()
.withProperty(10, Builder$.MODULE$.unassigned())
.build(Builder$.MODULE$.assigned());
build
方法必须检查是否分配了每个属性,因此当您泛化为多个属性时,它会变得很嘈杂:
The build
method has to check that every property is assigned, so it gets pretty noisy when you generalize to multiple properties:
Builder$.MODULE$.apply()
.withProp1(10, Builder$.MODULE$.unassigned())
.withProp2(20, Builder$.MODULE$.unassigned())
.withProp3(30, Builder$.MODULE$.unassigned())
// ...
.build(Builder$.MODULE$.assigned(),
Builder$.MODULE$.assigned(),
Builder$.MODULE$.assigned(),
//...
);
在帮助器类中有一些静态委托(以及一些静态导入),您应该可以将其简化为:
With some static delegates in a helper class (and some static imports), you should be able to get this down to something like:
createBuilder()
.withProp1(10, unassigned())
.withProp2(20, unassigned())
.build(assigned(), assigned());
这篇关于适用于Scala和Java的类型安全的生成器库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!