[英]Return class instance using generic inside companion object for method specified in trait
在Scala中,我想為使用泛型的特征中定義的方法返回類的實例,我的代碼示例如下:
文件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
}
基本上我想要的是一個接口,該接口具有在實現對象(恰好是擴展A
的類的伴隨對象)中返回類A
的具體實現的方法。
我為什么要把它放在物體上? ,是因為我想在不需要實例的情況下調用該方法(例如java中的靜態方法),因此我可以調用B.funct()
並使B類的實例類似於factory方法 ,對於其他實例擴展A
類(例如,對X.funct
的調用)將返回類X
的實例。
我試圖從函數定義中刪除泛型,除了函數的返回類型之外,只將其保留在特征定義中(例如def funct(): T
),但這也不起作用。
我對Scala還是很陌生,所以如果您能為假人解釋它並避免使用復雜的Scala獨特概念,我將不勝感激
簡單地說:
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()
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.