【问题标题】:Return class instance using generic inside companion object for method specified in trait使用泛型内部伴随对象为特征中指定的方法返回类实例
【发布时间】:2015-03-22 20:52:46
【问题描述】:

在 Scala 中,我想为使用泛型的 trait 中定义的方法返回一个类的实例,我的代码示例是这样的:

文件 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 类实例,对于扩展 A 的其他类,例如对 X.funct 的调用将返回类 X 的实例。

我试图从函数定义中删除泛型类型,除了函数的返回类型,并将其留在特征定义中(如def funct(): T),但这也不起作用。

我对 Scala 很陌生,所以如果你能解释一下,避免复杂的 scala 独特 概念,我将不胜感激

【问题讨论】:

    标签: scala generics


    【解决方案1】:

    简单地说:

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

    【讨论】:

    • 谢谢我让它工作了,只需将trait A 改成abstract class A(someParameter: String) 进行一些小改动,然后从object B 中的otherFunct 中删除冒号或添加String,请让我知道这是你想说的还是我错过了阅读
    • 冒号只是一个错字(已修复)。 abstract class/trait 更改只是因为它似乎与问题不太相关,所以我只是更改它以保存一些字符。
    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2023-01-12
    • 2019-07-24
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    相关资源
    最近更新 更多