使用sbt插件:
addSbtPlugin("com.felixmulder" % "sbt-dotty" % "0.1.9")在运行sbt console时,我尝试了新的联合类型特性:
Starting dotty interpreter...
Welcome to Scala.next (pre-alpha, git-hash: 606e36b) (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_112).
Type in expressions to have them evaluated.
Type :help for more information.
scala> case class A(val x: Int, y: Double)
defined class A
scala> case class B(val x: Int, y: String)
defined class B
scala> def getX(o: A | B): Int = o.x
-- [E008] Member Not Found Error: <console> ------------------------------------
8 |def getX(o: A | B): Int = o.x
| ^^^
| value `x` is not a member of (A | B)(o)为什么这个不行?我是不是用错了工会类型?只是还没起作用吗?
发布于 2017-03-08 06:51:53
我觉得这不应该真的起作用。如果A和B扩展了一个声明它们各自有一个x: Int的公共接口,它就会工作。
trait C { def x: Int }
case class A(x: Int, y: Double) extends C
case class B(x: Int, y: String) extends C
def getX(o: A | B): Int = o.x
scala> getX(A(1, 2))
val res0: Int = 1没有它,编译器需要仔细检查A和B,以确定它们是否定义了相同的x,这似乎不符合简化Scala类型系统的目标。
当然,支持文档几乎不存在,目前还没有完整的规范。我认为这张幻灯片可能是一个混乱的来源,因为它不是可编译的代码。
https://stackoverflow.com/questions/42663509
复制相似问题