在具体类中使用抽象类型? [英] Use of abstract type in a concrete class?

查看:51
本文介绍了在具体类中使用抽象类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala> class A { type T <: String; def f(a: T) = println("foo")}
defined class A

scala> (new A).f("bar")
<console>:9: error: type mismatch;
found   : java.lang.String("bar")
required: _1.T where val _1: A
             (new A).f("bar")
                       ^

A 类具有抽象类型 T,但不是抽象类.创建A 的对象(如图所示)并没有定义类型T.

Class A has an abstract type T, but is not an abstract class. Creating an object of A (as shown) does not define type T.

我的第一个想法是,我可以将任何类型作为 T 传递,它是 String 的子类,但我不是.那么对象中的 T 究竟是什么类型,我可以通过什么?

My first thought was, I am allowed to pass any type as T which is a subclass of String, but I am not. So what type actually is T in the object and what am I allowed to pass through ?

推荐答案

如你所说,A中的T是抽象的;因此,您将找不到任何可以放入方法 f 的值,直到您拥有 A 的子类型,它实际上修复了 T.

As you say, T in A is abstract; therefore you won't find any value you can put into method f, until you have a subtype of A which actually fixes T.

(new A { type T = String }).f("bar")

思路是可以依次细化类型:

The idea is that the type can be successively refined:

trait Var[A] { def get: A; def set(v: A): Unit }

trait Sys {
  type V[A] <: Var[A]

  def swap[A](x: V[A], y: V[A]): Unit = {
    val tmp = x.get
    x.set(y.get)
    y.set(tmp)
  }
}

trait HistVar[A] extends Var[A] { def created: java.util.Date }

trait HistSys extends Sys {
  type V[A] <: HistVar[A]

  def newest[A](x: V[A], y: V[A]): A =
    if (x.created after y.created) x.get else y.get
}

当然你的问题是好的——没有理由你想要一个类型参数不固定的类的具体实例化.我想不出一个有意义的案例.(当然,如果不涉及 T 类型,您仍然可以拥有可访问的功能)

But of course you're question is good -- there is no reason why you would want a concrete instantiation of a class whose type parameter is not fixed. I can't think of a case where that makes sense. (Well of course, you could still have functionality that is accessible, if it does not involve type T)

进一步搜索发现以下类似重复的SO question.您可以在那里找到对 Scala 票 的引用,其中将其概述为 '功能"--仍然没有显示此功能"实际上有用的情况:)

Further searching finds the following, quasi duplicate, SO question. You can find there a reference to a Scala ticket which outlines it as a 'feature' -- still doesn't show a case where this 'feature' is actually useful :)

这篇关于在具体类中使用抽象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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