Movatterモバイル変換


[0]ホーム

URL:


This page is no longer maintained — Please continue to the home page atwww.scala-lang.org

Home

Scala Main Menu

Home »A Tour of Scala » A Tour of Scala: Upper Type Bounds

A Tour of Scala: Upper Type Bounds

Created by admin on 2008-07-05. Updated: 2008-12-21, 01:15

In Scala, type parameters and abstract types may be constrained by a type bound. Such type bounds limit the concrete values of the type variables and possibly reveal more information about the members of such types. An upper type bound T <: Adeclares that type variable T refers to a subtype of type A.

Here is an example which relies on an upper type bound for the implementation of the polymorphic method findSimilar:

trait Similar {def isSimilar(x: Any): Boolean}case class MyInt(x: Int)extends Similar {def isSimilar(m: Any): Boolean =    m.isInstanceOf[MyInt] &&    m.asInstanceOf[MyInt].x == x}object UpperBoundTestextends Application {def findSimilar[T <: Similar](e: T, xs: List[T]): Boolean =if (xs.isEmpty)falseelse if (e.isSimilar(xs.head))trueelse findSimilar[T](e, xs.tail)val list: List[MyInt] = List(MyInt(1), MyInt(2), MyInt(3))  println(findSimilar[MyInt](MyInt(4), list))  println(findSimilar[MyInt](MyInt(2), list))}

Without the upper type bound annotation it would not be possible to call method isSimilar in method findSimilar.

The usage of lower type bounds is discussed here

Scala Quick Links

Featured News

User login


will be sent securely

Create new account

Retrieve lost password

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland


[8]ページ先頭

©2009-2026 Movatter.jp