鉴于以下特点:
scala> trait Foo {
| def f: Int => Int => Int
| }
defined trait Foo我创建了一个尝试实例化Foo#f的类
scala> class FooImpl extends Foo {
| override def f(x: Int, y: Int) = 100
| }
<console>:11: error: class FooImpl needs to be abstract, since method f in trait Foo of type => Int => (Int => Int) is not defined
class FooImpl extends Foo {
^我能够用以下方法解决这个问题:
scala> class FooImpl extends Foo {
| override def f = x => y => 100
| }
defined class FooImpl然后我可以做一个例子:
scala> new FooImpl().f(10)(20)
res3: Int = 100但是,我如何创建一个Foo的实现,该实现使用def f(x: Int, y: Int) = 100实现Foo#f,即无需运行?
最后,我尝试:
scala> trait Bar { def f: (Int, Int) => Int }
defined trait Bar但这也失败了:
scala> class BarImpl extends Bar {
| override def f(x: Int, y:Int) =100
| }
<console>:11: error: class BarImpl needs to be abstract, since method f in trait Bar of type => (Int, Int) => Int is not defined
class BarImpl extends Bar {
^发布于 2015-07-04 02:21:51
这些类型是不相容的。
def f: Int => Int => Int。。是一个无参数的方法,它返回带有一个参数Int的函数,返回带有一个参数Int的函数,返回Int。
def f: (Int, Int) => Int。。是一个无参数的方法,它返回带有Int类型的两个参数的函数,该参数返回Int。
def f(x: Int, y: Int): Int。。是一个具有两个Int参数的双参数方法,该方法返回一个Int。
所有这些都是从根本上不同的。您不能用任何其他方法覆盖其中的任何一个。如果您想要f(x: Int, y: Int): Int,那么首先应该是Foo中的签名。否则,您将不得不咖喱,eta-展开,或其他东西,以使签名匹配。
发布于 2015-07-04 02:20:09
如果您想要该特性定义非咖喱版本,那么它需要如下所示:
trait Foo {
def f(x: Int, y: Int): Int
}这里的(x: Int, y: Int)表示f接受Int的两个参数,: Int表示返回值需要是Int。
发布于 2016-04-13 10:12:49
这就是如何创建实现FooImpl特性的Foo。我们也可以访问Foo#f而无需运行。
trait Foo{
def f1:Int=> Int=> Int
def f2: (Int, Int) => Int
}
class FooImpl extends Foo{
//actual implementors of f1 and f2 in Foo trait
def g0=g1
def g1=g2
def g2=20
def add(a:Int, b:Int)=a+b
override def f1=g0=>g1=>g2
override def f2=add
}现在,我们可以实例化FooImpl类,而无需运行。
var x = new FooImpl
println(x.f1.apply(1).apply(1)) //results 20
println(x.f2(10,10)) //results 20https://stackoverflow.com/questions/31216143
复制相似问题