官术网_书友最值得收藏!

Existential types

Existential types come into play if we stop caring about the specifics of type parameters. Taking our previous example, if we have a method that expects a glass of something, but inside the method, we do not actually care what this something is, then we get the following:

def drink[T <: Water](g: Glass[T]): Unit = { g.contents; () }

In this definition, we actually don't need to know what T is, we just want to make sure that it is some kind of Water. Scala allows you to have an underscore as a placeholder, in the same way it can be utilized to denote unused variables:

def drink[_ <: Water](g: Glass[_]): Unit = { g.contents; () }

This is a placeholder syntax for existential types. As we saw previously, if the upper bound is omitted, scala.Any is assumed. In the case that the lower bound hasn't been defined, the compiler will implicitly add scala.Nothing.

This syntax is just a shorter version of the more powerful syntax T forSome { Q }, where Q is a sequence of type declarations, for example:

import scala.language.existentials
val glass = Full[T forSome { type T <: Water }](new Water(100))

Existential types are considered to be an advanced language feature and so need a respective import to be in scope or to be enabled as a compiler option.

主站蜘蛛池模板: 达州市| 万盛区| 伊通| 通山县| 娄烦县| 彰化市| 乌拉特前旗| 乌鲁木齐县| 白山市| 台安县| 吉林省| 耿马| 施甸县| 义马市| 临朐县| 育儿| 旬邑县| 景德镇市| 涞水县| 浦县| 永济市| 黄大仙区| 和平县| 手机| 枞阳县| 太白县| 泗阳县| 万山特区| 玉田县| 福安市| 开封市| 南充市| 隆子县| 托克逊县| 同心县| 长治市| 宁远县| 日土县| 长武县| 黄冈市| 遵义市|