如何使Scala类型参数推理更智能? [英] How to make scala type parameter inference smarter?

查看:83
本文介绍了如何使Scala类型参数推理更智能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数采用类型参数T,该参数必须是this.type的子类型:

I have a function that takes a type parameter T that has to be a subtype of this.type:

def injectFrom[T <: this.type](same: T): Unit = ...

但是每次我使用它时,编译器都会给我一个

however every time I use it, the compiler gave me a

无法推断出T型"错误

type T cannot be inferred" error

,每次都可以通过将T显式指定为(instance_variable).type进行修复.将来如何避免这样做?

and every time it can be fixed by specifying T explicitly as (instance_variable).type. How can I avoid doing this in the future?

推荐答案

this.type是单个对象或类实例的类型,而不是类的类型.

this.type is a type of an individual object or class instance, not of the class.

在以下代码中,a1a2将具有不同的this.type:

In the following code a1 and a2 will have different this.type:

class A
val a1 = new A()
val a2 = new A()

所以类型参数[T <: this.type]确实没有意义,因为您不能extend object或实例.

So type parameter [T <: this.type] doesn't really make sense as you can't extend an object or an instance.

如果要设计,以便子类中的函数只能接受该子类的实例(因此只能接受该子类的子类的实例),则必须使用类型形参或类型变量使类型显式:

If you want to have a design, so that functions in subclasses can accept only instances of that subclass (and consequently instances of subclasses only of that subclass) you would have to make the type explicit by using type parameter or type variable:

trait A {
    type Self
    def injectFrom(same: Self): Unit = ???
}
class B extends A {
    type Self = B
}
class C extends A {
    type Self = C
}

或Scala在

or something that Scala does for example in Ordered implementation:

trait A[Self] {
    def injectFrom(same: Self): Unit = ???
}
class B extends A[B]
class C extends A[C]

在两种情况下new B().injectFrom(new B())都可以编译,但new B().injectFrom(new C())不能编译.

In both cases new B().injectFrom(new B()) will compile but new B().injectFrom(new C()) won't.

第二个示例的修改,使您可以在A中包含this injectFrom this:

The modification of the second example that allows you to have this injectFrom this inside A:

trait A[Self] {
    def injectFrom(same: A[Self]): Unit = ???
    def test() {
        this injectFrom this
    }
}

这篇关于如何使Scala类型参数推理更智能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆