Scala中的类型 - 下限 [英] Types in Scala - lower bounds

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

问题描述



我的期望是 T 必须是 B 或 A ,所以调用 lowerBound(new D)应该不会编译(?)。类似的实验与上行给我预期typecheck错误。

感谢提示。

 对象varianceCheck {
类A {
改写DEF的toString = this.getClass.getCanonicalName
}

b类延伸A
C类延伸B
D类延伸C

def lowerBound [T> ;: B](param:T)= {param}

println(lowerBound(new D))//> varianceCheck.D
}


解决方案

你可以这样写:

  scala> def lowerBound [T>:B](param:T)= {param} 
lowerBound:[T> ;: B](param:T)T

scala>下界(新AnyRef {})
RES0:AnyRef = $匿名$ -1 @ 2eef224



,其中 AnyRef 是所有对象/引用类型的超类型(实际上它是Java Object class)的别名。这是正确的, T>:B 表示类型参数 T 或抽象类型 T 指的是一个超类型 B



使用 toString 的坏例子,因为这个方法有所有的对象类型,但是如果你改变它,让我们来说一下 someMethod ,您的 lowerBound 将无法编译:

 < console> ;: 18:错误:值的someMethod不是类型参数T 
DEF下界的成员[T计算值:b](PARAM:T)= {param.someMethod}

如果将其更改为 T <:B ,这意味着类型 T B 的子类,比一切都好,导致这个 param has someMethod method:

  def lowerBound [T <:B ](param:T)= {param.someMethod} 


on code below.

My expectation is that T must be a of type B or A, so call to lowerBound(new D) should probably not compile (?). Similar experiments with upperbound give me expected typecheck errors.

Thanks for giving the hint.

object varianceCheck {
  class A {
    override def toString = this.getClass.getCanonicalName
  }

  class B extends A
  class C extends B
  class D extends C

  def lowerBound[T >: B](param: T) = { param }

  println(lowerBound(new D))                      //> varianceCheck.D
}

解决方案

With your implementation you can write:

scala>   def lowerBound[T >: B](param: T) = { param }
lowerBound: [T >: B](param: T)T

scala> lowerBound(new AnyRef {})
res0: AnyRef = $anon$1@2eef224

where AnyRef is a super type of all object/reference types (actually it is an alias for Java Object class). And this is right, T >: B expresses that the type parameter T or the abstract type T refer to a supertype of type B.

You just have a bad example with toString, cause this method has all object types, but if you change it to, let's say on someMethod, your lowerBound won't compile:

<console>:18: error: value someMethod is not a member of type parameter T
       def lowerBound[T >: B](param: T) = { param.someMethod }

If you change this to T <: B, which means that parameter of type T is a subclass of B, than everything is good, cause this param has someMethod method:

def lowerBound[T <: B](param: T) = { param.someMethod }

这篇关于Scala中的类型 - 下限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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