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

  • Learn Scala Programming
  • Slava Schmidt
  • 228字
  • 2021-06-10 19:35:46

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.

主站蜘蛛池模板: 翼城县| 犍为县| 柳州市| 大竹县| 老河口市| 德化县| 中西区| 博爱县| 麻江县| 聂拉木县| 会同县| 游戏| 康马县| 孝义市| 齐齐哈尔市| 临漳县| 嘉禾县| 尖扎县| 五大连池市| 阿坝县| 台东县| 新闻| 齐齐哈尔市| 南靖县| 武穴市| 铁岭市| 方正县| 河北省| 德清县| 繁昌县| 平潭县| 宜春市| 商都县| 交城县| 尼木县| 施甸县| 靖西县| 饶平县| 南通市| 沽源县| 富源县|