Scala:用两种类型参数化的类型的简写

时间:2018-03-26 09:29:50

标签: scala

Scala允许使用以下类型:

=:=[Int, String] 

as:

Int=:=String

此功能似乎不限于此类型,我也可以举例如下:

type Or[A,B] = Either[A,B]
val x: Int Or String = Right("value")

这是如何工作的?

1 个答案:

答案 0 :(得分:6)

它有效as described in the specification。如果这太过于正式和过于抽象,那么这里只是一个简短的说明。

  1. 您可以对中缀类型使用任意标识符,因此以下所有定义均有效:

    type foobar[X, Y] = (X, Y)
    type <=[X, Y] = Y => X
    type !+?[X, Y] = (X, Y)
    type `or failure`[X, Err] = scala.util.Either[Err, X]
    
    val x: Int foobar String = (42, "hello world")
    val y: String <= Int = n => "#" * n
    val z: Int !+? Float = (42, 3.1415f)
    val w: Int `or failure` String = scala.util.Right(42)
    
  2. 中缀类型的参数不仅限于种类*,它也适用于更高级别的参数:

    type of[F[_], X] = F[X]
    val l1: List of Int = List(42)
    
  3. 没有运算符优先级。中缀类型都向左或向右关联:

    type +[A, B] = scala.util.Either[A, B]
    type *[A, B] = (A, B)
    
    // It's     ((Int * String) + Float) * Double
    // It's NOT (Int * String) + (Float * Double)
    val a: Int * String + Float * Double =
      (scala.util.Left((42, "foo")), 1.0d)
    
  4. :结尾的中缀类型与右侧相关联:

    type -:[A, B] = B => A
    
    val f: String -: Int -: Double =
      (g: (Double => Int)) => "foo" * g(42d)
    
    // Not: (g: Double) => (i: Int) => "foo"
    
  5. 左关联和右关联中缀运算符不能混合使用:

    // error: left- and right-associative operators
    // with same precedence may not be mixed
    val wontCompile: Int * Int -: Int = i => (i, i)