REPL中如何触发中缀类型显示

How to trigger infix type display in REPL

如果我使用两个参数创建自己的类型:

class !:[A, B]

然后在 REPL 中创建它的实例并没有按照我想要的方式显示它的类型:

scala> new !:[Int, Int]
res18: !:[Int,Int] = $bang$colon@5eb1479

相反,我希望它显示如下:

scala> new !:[Int, Int]
res18: Int !: Int = $bang$colon@5eb1479

这在 Scala 中可行吗?

不确定这是否有帮助,但您可以覆盖 toString 方法并控制输出的第二部分,如下所示:

import scala.reflect.runtime.universe.{TypeTag, typeOf}

class A[X, Y] (implicit val tt: TypeTag[X], implicit val ty: TypeTag[Y]) {
  override def toString() = typeOf[X] + " !: " + typeOf[Y]
}
new A[Int, Int]()

产出

res15: A[Int,Int] = Int !: Int

符号类型的中缀显示在 Scala 2.12.2 中是默认的。更改是在 this pull request 中进行的。

它还在包 scala.annotation 中添加了注解 showAsInfix,以便您在需要更改默认行为的情况下进行控制。