作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
首先是背景——我正在编写一些代码来解码从套接字接收到的消息。套接字的性质意味着这些作为 ByteString
接收的消息可能是完整的、被截断的或与其他消息连接的。消息本身被分解为一个公共(public) header ,其中包含后面的可变数据的长度。
我的计划是让函数读取消息的各个部分,例如,第一次读取可以读取可变数据的长度,第二次读取可变数据本身。
当调用其中一个方法时,我希望它返回下一个操作,该操作可能是读取序列中的下一个逻辑操作,或者如果由于尚未接收到所有所需数据而无法执行特定读取,则返回其自身.
如果从套接字接收到的数据是完全成帧的,读取操作将在readLength
和readData
之间交替。但是,当从套接字中以多个 block 读取数据时,读取操作可能遵循 readLength
、readData
和 readData
模式。
希望这是有道理的。
我想做的是这样的(由于循环引用而无法编译):
type ReadFunction = (ByteBuffer) => ReadFunction
这样我就可以声明这样的东西:
def readLength(buffer: ByteBuffer): ReadFunction = {
if (buffer.limit - buffer.position > 4) {
return readData(buffer.getInt)
}
else {
return readLength
}
}
def readData(length: Int)(buffer: ByteBuffer): ReadFunction = {
if (buffer.limit - buffer.position > length) {
val data: Array[Byte](size)
buffer.get(data)
//process data
readLength
}
else {
readData(length)
}
}
现在我知道我可以(并且实际上已经)通过将读取操作定义为类来解决这个问题,这些类扩展了一个共同特征并返回每个特征的实例,但这看起来不像 Scala。
所以我的问题是 - 如何定义一个可以返回自身的函数?
最佳答案
不能在type
声明中使用循环引用,但可以在class
或trait
声明中使用它,如下所示:
implicit class ReadFunction(f: Int => ReadFunction) extends (Int => ReadFunction) {
def apply(i: Int) = f(i)
}
lazy val read: ReadFunction = { i: Int => println(i); read }
scala> read(1)(2)(3)
1
2
3
res0: ReadFunction = <function1>
关于scala - 如何在 Scala 中声明一个返回自身的函数(或另一个具有相同签名的函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20093425/
我是一名优秀的程序员,十分优秀!