小编Mau*_*abo的帖子

Scala中的结构化键入不适用于Double?

我正在尝试执行以下代码:

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)

我的代码有问题吗?

scala

11
推荐指数
2
解决办法
411
查看次数

具有两个条件的Scala List.filter,仅应用一次

不知道这是否可行,但我有一些这样的代码:

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

10
推荐指数
2
解决办法
2万
查看次数

使用Scala宏或反射实例化一个类

在我的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)

可能吗?

reflection macros scala scala-macros

7
推荐指数
1
解决办法
960
查看次数

标签 统计

scala ×3

macros ×1

reflection ×1

scala-macros ×1