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

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.

主站蜘蛛池模板: 汉源县| 南宫市| 辽阳县| 积石山| 鹤壁市| 葵青区| 乃东县| 江安县| 融水| 缙云县| 弋阳县| 黔西县| 喀什市| 河池市| 京山县| 化隆| 铁力市| 调兵山市| 泾阳县| 彭泽县| 苍梧县| 星座| 东至县| 海淀区| 肇庆市| 吉木萨尔县| 宣化县| 华阴市| 敦化市| 尼玛县| 松原市| 东光县| 紫金县| 广灵县| 铁岭县| 莱芜市| 鹰潭市| 三江| 昭平县| 新野县| 乌鲁木齐市|