- 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.
- PostgreSQL Cookbook
- Web Development with Django Cookbook
- MySQL數(shù)據(jù)庫(kù)管理與開發(fā)實(shí)踐教程 (清華電腦學(xué)堂)
- C語(yǔ)言程序設(shè)計(jì)學(xué)習(xí)指導(dǎo)與習(xí)題解答
- 微信小程序項(xiàng)目開發(fā)實(shí)戰(zhàn)
- 網(wǎng)站構(gòu)建技術(shù)
- Hands-On Functional Programming with TypeScript
- Unity Game Development Scripting
- PLC應(yīng)用技術(shù)(三菱FX2N系列)
- Python爬蟲、數(shù)據(jù)分析與可視化:工具詳解與案例實(shí)戰(zhàn)
- 21天學(xué)通C++(第5版)
- Cocos2d-x Game Development Blueprints
- 分布式架構(gòu)原理與實(shí)踐
- Greenplum構(gòu)建實(shí)時(shí)數(shù)據(jù)倉(cāng)庫(kù)實(shí)踐
- 現(xiàn)代CPU性能分析與優(yōu)化