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

Mat*_*oob 1 scala

Scala允许使用以下类型:

=:=[Int, String] 
Run Code Online (Sandbox Code Playgroud)

如:

Int=:=String
Run Code Online (Sandbox Code Playgroud)

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

type Or[A,B] = Either[A,B]
val x: Int Or String = Right("value")
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

And*_*kin 6

它的工作原理如说明书中所述.如果这是过于正式和过于抽象,这里只是简单说明它的内容.

  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)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 中缀类型的参数不仅限于种类*,它也适用于更高级的参数:

    type of[F[_], X] = F[X]
    val l1: List of Int = List(42)
    
    Run Code Online (Sandbox Code Playgroud)
  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)
    
    Run Code Online (Sandbox Code Playgroud)
  4. :以右侧关联的中缀类型:

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

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