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

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

Infix types

In the same way that Scala has infix operators, it has infix types. An infix type, such as Op B, is just any type that has exactly two type operands. It is equivalent to the type defined as Op[A, B]Op may be any valid identifier.

The type operators have the same associativity as term operators—they are left associative unless an operator ends in : (colon), in which case it is right associative. Consecutive infix operators must have the same associativity. Let's look at an example to understand what this means:

type Or[A, B]
type And[A, B]
type +=[A, B] = Or[A, B]
type =:[A, B] = And[A, B]

type CC = Or[And[A, B], C]
type DA = A =: B =: C
type DB = A And B And C

// type E = A += B =: C // wrong associativity
type F = (A += B) =: C

Here, we defined four types, all of which have two type parameters and so can be used as infix types. Then, we define a type called CC, which expresses some relation between the A, B, and C types. The DA and DB type definitions show what the type definition looks like in infix notation. The first attempt to define some type, E, to be the same as the C type fails because of the different associativity of the types, =+ and =:, and we have demonstrated how parentheses can be used to work around this rule.

If used properly, infix types can greatly improve the readability of the code:

type |[A, B] = Or[A, B]
type [A, B] = And[A, B]
type G = A B | C

Here, we can see how infix types allow you to define type relation in a way that looks similar to Boolean operations.

主站蜘蛛池模板: 六盘水市| 汶川县| 游戏| 游戏| 耒阳市| 湘潭县| 镇赉县| 扶风县| 奉节县| 翁牛特旗| 平利县| 平邑县| 普兰店市| 金阳县| 建德市| 揭阳市| 河西区| 凤翔县| 和平县| 遂川县| 都江堰市| 鄂尔多斯市| 祥云县| 西青区| 镇赉县| 洞头县| 舞阳县| 肥城市| 普兰县| 蓬溪县| 太白县| 琼海市| 永寿县| 阿荣旗| 兴安盟| 杭锦旗| 工布江达县| 都江堰市| 南华县| 黄梅县| 罗山县|