我正在尝试执行以下代码:
def sum(e: { def *(x: Double): Double}) = e * 2.0
Run Code Online (Sandbox Code Playgroud)
问题是,这不适用于任何数字类:
sum(20.0)
<console>:9: error: type mismatch;
found : Double(10.0)
required: AnyRef{def *(x: Double): Double}
algo(10.0)
sum(10)
<console>:9: error: type mismatch;
found : Int(10)
required: AnyRef{def *(x: Double): Double}
algo(10)
Run Code Online (Sandbox Code Playgroud)
我的代码有问题吗?
不知道这是否可行,但我有一些这样的代码:
val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
val evens = list.filter { e => e % 2 == 0 }
if(someCondition) {
val result = evens.filter { e => e % 3 == 0 }
} else {
val result = evens.filter { e => e % 5 == 0 }
}
Run Code Online (Sandbox Code Playgroud)
但是我不想迭代所有元素两次,所以有没有办法让我可以在这个集合上创建"泛型选择全部数字"并应用其他一些函数,这样它只会迭代一次?
在我的scala代码中,我希望能够实例化一个新类.例如,我有以下代码:
class Foo { def foo=10 }
trait Bar { val bar=20 }
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望能够做到这样的事情:
def newInstance[A <: Foo] = { new A with Bar }
newInstance[Foo]
Run Code Online (Sandbox Code Playgroud)
但是,当然这不起作用.我试图使用反射来实例化一个类,但似乎我只能实例化一个新类(而不是与特征混合).我认为可以使用宏来完成这项工作,但我不确定从哪里开始.
我想要做的是像下面的Ruby代码:
class SomeClass
def create
self.class.new
end
end
class Other < SomeClass
end
Other.new.create # <- this returns a new Other instance
Run Code Online (Sandbox Code Playgroud)
可能吗?