抽象函数的可变数量的参数 [英] Variable number of arguments for an abstract function
问题描述
我有以下代码:
trait TypeLike
trait ArgLike
trait Predicate{
def name:String
}
case class Arg(name:String)
case class Predicate1[I1<:Arg,O<:TypeLike](name:String, arg1:I1, output:O, func: I1=> O) extends Predicate
case class Predicate2[I1<:Arg,I2<:Arg,O<:TypeLike](name:String, arg1:I1,arg2:I2, output:O, func: (I1,I2)=> O)
extends Predicate
如何将 "func" 放入 Predicate trait.我不知道如何定义具有可变数量输入的抽象函数.
How can I put "func" in Predicate trait. I don't know how to define an abstract function with variable numbers of input.
推荐答案
不幸的是,您必须为此使用 HList.下面是一个 Shapeless HLists 的例子:
Unfortunately you'll have to use HLists for that. Here is an example with Shapeless HLists:
import shapeless._
trait Predicate[Args <: HList, O <: TypeLike] {
implicit val lubWitness: LUBConstraint[Args, Arg]
def name: String
def func: Args => O
}
case class Predicate1[I1 <: Arg, O <: TypeLike](
name: String,
arg1: I1,
output: O,
func: I1 :: HNil => O
) extends Predicate[I1 :: HNil, O] {
implicit val lubWitness = implicitly[LUBConstraint[I1 :: HNil, Arg]]
}
case class Predicate2[I1 <: Arg, I2 <: Arg, O <: TypeLike](
name: String,
arg1: I1,
arg2: I2,
output: O,
func: I1 :: I2 :: HNil => O
) extends Predicate[I1 :: I2 :: HNil, O] {
implicit val lubWitness = implicitly[LUBConstraint[I1 :: I2 :: HNil, Arg]]
}
// Example instantiation
val p1 = Predicate1("Example", Arg("test"), new TypeLike {},
(args: Arg :: HNil) => { println(args(0)); ??? })
说明
那么这里发生了什么?HList 基本上是立体对象的元组.让我们看看我们的例子:
So what happens here? An HList is basically a tuple on stereoids. Let's look at the example we have:
trait Predicate[Args <: HList, O <: TypeLike] {
Args <: HList
表示 Args
是一个类型列表.O <: TypeLike
是一个普通的有界限的类型参数.
Args <: HList
means Args
is a list of types. O <: TypeLike
is a normal type parameter with a bound.
implicit val lubWitness: LUBConstraint[Args, Arg]
这表示我们需要证明 HList Args
中的每个类型都是 Arg
的子类型(我假设这是一个要求.
This says that we need a proof that every type in the HList Args
is a subtype of Arg
(I was assuming this is a requriement.
def func: Args => O
一个函数,它接受一个shape"的 HList Args
并返回一个 O
.(如果你愿意,你也可以把它写成一个方法.
A function that takes a HList of "shape" Args
and returns a O
. (You can also write this as a method if you prefer.
case class Predicate1 /*snip*/ extends Preciate[I1 :: HNil, O]
Predicate1
是一个 Predicate
,其参数列表包含一个 I1
类型的元素.
Predicate1
is a Predicate
whose argument list contains one element of type I1
.
implicit val lubWitness = implicitly[LUBConstraint[I1 :: HNil, Arg]]
检索并定义I1
是Arg
的子类型的见证(这是这种情况,由于Predicate1
声明中的类型绑定)代码>.
Retrieve and define a witness that I1
is a subtype of Arg
(which is the case, due to the type bound in the declaration of Predicate1
.
这篇关于抽象函数的可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!