繁体   English   中英

使用trait对象中指定的方法的通用内部伴侣对象返回类实例

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM