新聞中心
本篇內(nèi)容主要講解“scala的類型上下界是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“scala的類型上下界是什么”吧!

創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比莒縣網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式莒縣網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋莒縣地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。
類型上界
在Scala中,類型參數(shù)和抽象類型都可以有一個(gè)類型邊界約束。這種類型邊界在限制類型變量實(shí)際取值的同時(shí)還能展露類型成員的更多信息。比如像T <: A這樣聲明的類型上界表示類型變量T應(yīng)該是類型A的子類。下面的例子展示了類PetContainer的一個(gè)類型參數(shù)的類型上界。
abstract class Animal {def name: String}abstract class Pet extends Animal {}class Cat extends Pet {override def name: String = "Cat"}class Dog extends Pet {override def name: String = "Dog"}class Lion extends Animal {override def name: String = "Lion"}class PetContainer[P <: Pet](p: P) {def pet: P = p}val dogContainer = new PetContainer[Dog](new Dog)val catContainer = new PetContainer[Cat](new Cat)
// this would not compileval lionContainer = new PetContainer[Lion](new Lion)
類PetContainer接受一個(gè)必須是Pet子類的類型參數(shù)P。因?yàn)镈og和Cat都是Pet的子類,所以可以構(gòu)造PetContainer[Dog]和PetContainer[Cat]。但在嘗試構(gòu)造PetContainer[Lion]的時(shí)候會(huì)得到下面的錯(cuò)誤信息:
type arguments [Lion] do not conform to class PetContainer's type parameter bounds [P <: Pet]
這是因?yàn)長ion并不是Pet的子類。
類型下界
trait Node[+B] {def prepend(elem: B): Node[B]}case class ListNode[+B](h: B, t: Node[B]) extends Node[B] {def prepend(elem: B): ListNode[B] = ListNode(elem, this)def head: B = hdef tail: Node[B] = t}case class Nil[+B]() extends Node[B] {def prepend(elem: B): ListNode[B] = ListNode(elem, this)}
trait Node[+B] {def prepend[U >: B](elem: U): Node[U]}case class ListNode[+B](h: B, t: Node[B]) extends Node[B] {def prepend[U >: B](elem: U): ListNode[U] = ListNode(elem, this)def head: B = hdef tail: Node[B] = t}case class Nil[+B]() extends Node[B] {def prepend[U >: B](elem: U): ListNode[U] = ListNode(elem, this)}
trait Bird case class AfricanSwallow() extends Bird case class EuropeanSwallow() extends Bird val africanSwallowList= ListNode[AfricanSwallow](AfricanSwallow(), Nil()) val birdList: Node[Bird] = africanSwallowList birdList.prepend(EuropeanSwallow())
到此,相信大家對“scala的類型上下界是什么”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
網(wǎng)站標(biāo)題:scala的類型上下界是什么
文章轉(zhuǎn)載:http://www.dlmjj.cn/article/pjeses.html


咨詢
建站咨詢
