gpt4 book ai didi

scala - 在 Scala 中从结构上识别类型

转载 作者:行者123 更新时间:2023-12-02 09:25:45 26 4
gpt4 key购买 nike

我正在阅读 Martin Odersky 关于 Scala 类型系统的采访,其中提到了以下内容

One of the aspects where Scala is more expressive than Java is that it lets you express these things. In Scala it is possible to have a type that says: anything with a close method that takes no parameter and returns Unit (which is similar to void in Java). You can also combine it with other constraints. You can say: anything inheriting from a particular class that in addition has these particular methods with these signatures. Or you can say: anything inheriting from this class that has an inner class of a particular type. Essentially, you can characterize types structurally by saying what needs to be in the types so that you can work with them.

有人可以在 Scala 中编写一个片段来展示如何从结构上表征类型吗?读完之后我感觉我应该能够做到以下几点:

type CanClose { def close: Unit }
val closeableFile: CanClose = new File()
val closeableStream: CanClose = new Stream()

最佳答案

在 Scala 中,类型可以通过其结构来识别,从而实现通常所说的鸭子类型。

这是一个例子

scala> def close(x: { def close: Unit }): Unit = x.close
warning: there was one feature warning; re-run with -feature for details
close: (x: AnyRef{def close: Unit})Unit

scala> class CanBeClosed {
| def close: Unit = println("I'm closed now")
| }
defined class CanBeClosed

scala> class CannotBeClosed {
| }
defined class CannotBeClosed

scala> close(new CanBeClosed)
I'm closed now

scala> close(new CannotBeClosed)
<console>:13: error: type mismatch;
found : CannotBeClosed
required: AnyRef{def close: Unit}
close(new CannotBeClosed)

但是,请务必注意,结构类型是使用运行时反射实现的,因此可能会对性能产生影响。

这就是为什么您在第一个定义时收到警告(您可以通过导入 import scala.language.reflectiveCalls 来消除警告)

关于scala - 在 Scala 中从结构上识别类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com