[英]Scala - defining own infix operators
采用单个参数的方法可以写为Scal中的中缀运算符。 即将*(other:C) = foo(this, other)
到C类,将允许我们编写c1 * c2
而不是foo(c1,c2)。 但是有没有办法在现有的类上定义中缀操作符,而这些操作符无法修改?
例如,如果我想写c1 + c2
而不是xor(c1,c2)
,其中c1,c2:Array[Byte]
,我显然无法修改Array-Class。
我发现了这个并尝试过
implicit class Bytearray(a1:Array[Byte]) extends Anyval {
def +(a2:Array[Byte]) = xor(a1,a2)
}
但这似乎不起作用( c1 + c2
)。
类型不匹配,预期:字符串,实际:数组[字节]
我想也许问题是我的使用+
,所以我交换它为xor
但c1 xor c2
只导致
无法解析符号xor
有什么建议?
UPDATE
有趣。 我有一个class Foo
,其下面定义了一个object Foo
,包含隐式类。 这导致上述错误。
但是 ,删除对象,而是将隐式类放入trait BytearrayHandling
然后扩展它( class Foo extends BytearrayHandling
)似乎工作。 这是为什么?
它应该直接使用扩展方法的正常声明:
implicit class ByteArrayOps(private val a1: Array[Byte]) extends AnyVal {
def + (a2: Array[Byte]): Array[Byte] =
(a1 zip a2).map { case (x, y) => (x ^ y).toByte }
}
"foo".getBytes + "bar".getBytes // Array(4, 14, 29)
但请注意,有时你会碰到这个:
类型不匹配,预期:字符串,实际:X
这是因为隐式转换可以通过将其转换为String来实现+
任何内容。 我放弃 了 试图 了解如何停用它。 如果我没弄错的话,它最终会进入Scala 2.12。
正如eugener所指出的,此错误消息可能表示您尚未实际导入扩展方法(隐式转换)。 例如:
object MyStuff {
implicit class ByteArrayOps(private val a1: Array[Byte]) extends AnyVal {
def + (a2: Array[Byte]): Array[Byte] =
(a1 zip a2).map { case (x, y) => (x ^ y).toByte }
}
}
"foo".getBytes + "bar".getBytes // error
得到:
<console>:14: error: type mismatch;
found : Array[Byte]
required: String
"foo".getBytes + "bar".getBytes
^
因为这个Predef
转换。 import MyStuff.ByteArrayOps
,它可以正常工作。
你可以这样做:
class ByteArray(self: Array[Byte]) {
def +(other: Array[Byte]) = Array[Byte](1, 2, 3) // replace with your code
}
implicit def byteArrayPlus(self: Array[Byte]) = new ByteArray(self)
Array[Byte](0, 1, 2) + Array[Byte](0, 2, 3)
最后一行应该产生Array(1, 2, 3)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.