[英]Return class instance using generic inside companion object for method specified in trait
In Scala I want to return a instance of a class for a method defined in a trait which uses generics, the code example I have is this: 在Scala中,我想为使用泛型的特征中定义的方法返回类的实例,我的代码示例如下:
File 1 文件1
package packOne
import packTwo.A
trait MyTrait[T <: MyTrait[T <: A]] {
def otherFunct(): String
def funct[T <: A](): T
}
File 2 文件2
package packTwo
import packOne.MyTrait
abstract class A(someParameter: String) {}
class B(someParameter: String) extends A(someParameter) {}
object B extends MyTrait[B] { // <--- the B inside MyTrait here is the class not the object, or at least that is what I want
def otherFunct(): String = "Hello"
def funct[B](): C = new B("hi") // <--- I think here is the key
}
basically what I want is an interface that have method to return a concrete implementation of class A
, in an implementing object (which happen to be a companion object for a class extending A
) . 基本上我想要的是一个接口,该接口具有在实现对象(恰好是扩展
A
的类的伴随对象)中返回类A
的具体实现的方法。
Why do I want that to be on an object? 我为什么要把它放在物体上? , is because I want to call that method without the need of an instance (like an static method in java), so that I can call
B.funct()
and have an instance of B class kind of like a factory method , for other classes extending A
for example a call to X.funct
will return an instance of class X
. ,是因为我想在不需要实例的情况下调用该方法(例如java中的静态方法),因此我可以调用
B.funct()
并使B类的实例类似于factory方法 ,对于其他实例扩展A
类(例如,对X.funct
的调用)将返回类X
的实例。
I have tried to remove the generic type from the function definition except on the return type of the function and just leave it in the trait definition (like def funct(): T
) but that does not work either. 我试图从函数定义中删除泛型,除了函数的返回类型之外,只将其保留在特征定义中(例如
def funct(): T
),但这也不起作用。
I am quite new to Scala so if you could explain it for dummies and avoid complex scala unique concepts I would appreciate 我对Scala还是很陌生,所以如果您能为假人解释它并避免使用复杂的Scala独特概念,我将不胜感激
How about simply: 简单地说:
trait A
class B(someParameter: String) extends A
trait MyTrait[T <: A] {
def otherFunct: String //Parentheses on parameterless methods with no side effects and no serious computation are generally unidiomatic in Scala
def funct: T //Note, no generic parameter on this method
}
object B extends MyTrait[B] {
def otherFunct = "Hello"
def funct = new B("hi")
}
And then: 接着:
B.funct //returns a new `B`
The apply
method is often used in this factory style (eg Seq.apply()
which is equivalent to Seq()
) apply
方法通常以这种工厂风格使用(例如Seq.apply()
等效于Seq()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.