Return class 实例使用泛型内部伴随对象用于特征中指定的方法
Return class instance using generic inside companion object for method specified in trait
在 Scala 中,我想 return 一个 class 的实例,用于在使用泛型的特征中定义的方法,我有代码示例这是:
文件 1
package packOne
import packTwo.A
trait MyTrait[T <: MyTrait[T <: A]] {
def otherFunct(): String
def funct[T <: A](): T
}
文件 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
}
基本上我想要的是一个接口,它有方法 return class A
的具体实现,在一个实现对象 中(恰好是class 扩展 A
) 的伴生对象。
为什么我希望它在对象上?,是因为我想在不需要实例的情况下调用该方法(就像 [=51 中的静态方法) =]),这样我就可以调用 B.funct()
并拥有一个 B class 的实例,有点像 工厂方法 ,对于其他 classes扩展 A
例如调用 X.funct
将 return class X
.
的一个实例
我试图从函数定义中删除泛型类型,函数的 return 类型除外,并将其保留在特征定义中(如 def funct(): T
),但这不起作用要么。
我对 Scala 很陌生,所以如果你能为傻瓜解释它并避免复杂的 scala unique 概念,我将不胜感激
简单的怎么样:
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")
}
然后:
B.funct //returns a new `B`
apply
方法在这种工厂风格中经常使用(例如Seq.apply()
相当于Seq()
)
在 Scala 中,我想 return 一个 class 的实例,用于在使用泛型的特征中定义的方法,我有代码示例这是:
文件 1
package packOne
import packTwo.A
trait MyTrait[T <: MyTrait[T <: A]] {
def otherFunct(): String
def funct[T <: A](): T
}
文件 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
}
基本上我想要的是一个接口,它有方法 return class A
的具体实现,在一个实现对象 中(恰好是class 扩展 A
) 的伴生对象。
为什么我希望它在对象上?,是因为我想在不需要实例的情况下调用该方法(就像 [=51 中的静态方法) =]),这样我就可以调用 B.funct()
并拥有一个 B class 的实例,有点像 工厂方法 ,对于其他 classes扩展 A
例如调用 X.funct
将 return class X
.
我试图从函数定义中删除泛型类型,函数的 return 类型除外,并将其保留在特征定义中(如 def funct(): T
),但这不起作用要么。
我对 Scala 很陌生,所以如果你能为傻瓜解释它并避免复杂的 scala unique 概念,我将不胜感激
简单的怎么样:
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")
}
然后:
B.funct //returns a new `B`
apply
方法在这种工厂风格中经常使用(例如Seq.apply()
相当于Seq()
)