简体   繁体   中英

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:

File 1

package packOne

import packTwo.A

trait MyTrait[T <: MyTrait[T <: A]] {
    def otherFunct(): String
    def funct[T <: A](): T
}

File 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 ) .

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 .

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.

I am quite new to Scala so if you could explain it for dummies and avoid complex scala unique concepts I would appreciate

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() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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