【发布时间】:2014-10-12 00:49:50
【问题描述】:
我想在 Scala 中定义一个适用于自定义类的运算符。类似于scala的Array utility methods,比如Array concatenation:
val (a, b) = (new Array[Int](4), new Array[Int](3))
val c = Array.concat(a, b)
我想模糊地定义一个运算符如下:
class MyClass {
def op():MyClass = {
// for instance,,
return new MyClass();
}
}
被调用,例如
val x = MyClass.op()
提供一个更具体的例子,假设 MyClass 是 MyAbstractClass 的扩展
// Provided as a utility for the more relevant code below.
def randomBoolean():Boolean = {
val randomInt = Math.round(Math.random()).toInt
if (randomInt == 1 ) return true;
else return false;
}
abstract class MyAbstractClass[T](size:Int) {
val stuff = new Array[T](size)
def randomClassStuff():Array[T]
}
class MyClass(size:Int) extends MyAbstractClass[Boolean](size) {
def randomClassStuff():Array[Boolean] = {
return new Array[Boolean](size) map {x => randomBoolean()}
}
}
我意识到我可以定义一个名为 MyClass 的对象,并在其中定义一个名为 randomClassStuff 的函数,但我宁愿利用抽象类来要求抽象类的扩展提供一种创建特定于特定对象的随机内容的方法那个类。
【问题讨论】:
-
1.我糊涂了。问题是什么?
-
2.这三个代码示例看起来都非常不同,而且完全没有相似之处。
-
3.你的最后一句话准确地描述了你做了什么。
-
我假设您的意思是您想要第三个 sn-p 的功能,以及第二个的语法?看我的回答
-
我给了你第一个的语法和第三个和第二个的组合功能。我回答的最后两行看起来像你的前两行。
标签: scala oop abstract-class