scala上界_Scala方差,上界和下界

scala上界

Variance refers as how subtyping between complex types relates to subtypes of their components. Scala supports variances annotations of type parameters of a generic class.

差异是指复杂类型之间的子类型如何与其组成部分的子类型相关。 Scala支持泛型类的类型参数的方差注释。

The type of variance annotations supported in Scala are;

Scala支持的方差注释的类型是;

TypesDefinitionScala Notation
CovariantC[T’] is a subclass of C[T][+T]
ContravariantC[T] is a subclass of C[T’][-T]
InvariantC[T] and C[T’] are not related[T]
种类 定义 Scala符号
协变 C [T']是C [T]的子类 [+ T]
逆变的 C [T]是C [T']的子类 [-T]
不变的 C [T]和C [T']不相关 [T]
class Array[+X] {
  def add[Y >: X](elem: Y): Array[Y] = new Array[Y] {
    override def first: Y = elem
    override def retrieve: Array[Y] = Array.this
    override def toString() = elem.toString() + "\n" + Array.this.toString()
  }
  def first: X = sys.error("No elements in the Array")
  def retrieve: Array[X] = sys.error("Array is empty")
  override def toString() = ""
}
object ArrayTest extends App {

  var a: Array[Any] = new Array().add("US");
  //a = a.add(new Object())
  a = a.add(56)
  a = a.add(67.89)
  println("Array elements added are: " + a)

}

The annotation +X indicates that X can be used in covariant positions only. The annotation -X indicates that X can be used in contravariant positions only. Array[X] is a subtype of S if X is a subtype of S.

注释+ X表示X只能在协变位置使用。 注释-X表示X只能在相反位置使用。 如果X是S的子类型,则Array [X]是S的子类型。

In this example we are defining a covariant type parameter X to define the method add. We have a polymorphic method in which we use the element type X as a lower bound of add method type variable thereby bringing the variance of X in sync with its declaration as covariant parameter. We are inserting elements of String,Integer and float types.

在此示例中,我们定义了协变类型参数X来定义方法add。 我们有一个多态方法,其中我们使用元素类型X作为add方法类型变量的下限,从而使X的方差与其声明为协变参数同步。 我们正在插入String,Integer和float类型的元素。

上限类型界限 (Upper type Bounds)

An upper type bound X <: B declares that type variable X refers to a subtype of type B.

类型上限X <:B声明类型变量X引用类型B的子类型。

Consider an example below.

考虑下面的示例。

trait Employee {
  def EmployeeIdexists(x: Any): Boolean
}

case class EId(a: Int) extends Employee {
  def EmployeeIdexists(x: Any): Boolean =
    x.isInstanceOf[EId] &&
      x.asInstanceOf[EId].a == a
}

object TestEmployee extends App {
  def findEId[A <: Employee](d: A, ls: List[A]): Boolean =
    if (ls.isEmpty) false
    else if (d.EmployeeIdexists(ls.head)) true
    else findEId[A](d, ls.tail)
  val elist: List[EId] = List(EId(25), EId(26), EId(27), EId(28))
  if ((findEId[EId](EId(28), elist)))
    println("Employee Id exists")
  else println("Employee Id does not exist")

}

This example find whether the employee id exists or not. We are defining a method findEId which creates an integer list and checks whether the id specified is contained in the list.

本示例查找员工ID是否存在。 我们正在定义一个findEId方法,该方法创建一个整数列表并检查指定的ID是否包含在列表中。

下界 (Lower type Bounds)

The term X >: B expresses that the type parameter X or the abstract type X refer to a supertype of type B. Lower type bounds declare a type to be a supertype of another type.

术语X>:B表示类型参数X或抽象类型X引用类型B的超类型。类型下限声明一个类型为另一种类型的超类型。

Create the scala class ListNode as;

将scala类ListNode创建为;

case class ListNode[+T](h: T, t: ListNode[T]) {
  def head: T = h
  def tail: ListNode[T] = t
  def prepend[U >: T](elem: U): ListNode[U] =
    ListNode(elem, this)
}

We are creating a class ListNode and defining the prepend method where T only appears in covariant positions. U >: T specifies the abstract type U is a supertype of T.

我们正在创建一个类ListNode并定义prepend方法,其中T仅出现在协变位置。 U>:T指定抽象类型U是T的超类型。

The type variable T appears as a parameter type of method prepend, this rule is broken. With the help of a lower type bound, though, we can implement a prepend method.

类型变量T作为方法前缀的参数类型出现,此规则已损坏。 但是,借助于下限类型的边界,我们可以实现prepend方法。

Now create a scala object as;

现在创建一个scala对象为;

object LowerBoundTest extends App {

  val empty: ListNode[Null] = ListNode(null, null)
  val strList: ListNode[String] = empty.prepend("hello")
    .prepend("world")
  val anylist: ListNode[Any] = strList.prepend(12345)
  println(strList)
  println(anylist)
}

That’s all for now, we will look into more scala features in future posts.

到目前为止,仅此而已,我们将在以后的文章中研究更多scala功能。

翻译自: https://www.journaldev.com/8924/scala-variances-upper-type-bounds-and-lower-type-bounds

scala上界

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值