Use*_*291 3 scala operators infix-notation infix-operator implicit-conversion
采用单个参数的方法可以写为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)
}
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用(c1 + c2).
类型不匹配,预期:字符串,实际:数组[字节]
我想也许这个问题是我使用的+,所以我交换了它,xor
但c1 xor c2只是导致了
无法解析符号xor
有什么建议?
UPDATE
有趣.我有一个class Foo与object Foo它下面的定义中,包含隐含的类.这导致上述错误.
但是,删除对象,而是将隐式类放入a 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)
Run Code Online (Sandbox Code Playgroud)
但请注意,有时你会碰到这个:
类型不匹配,预期:字符串,实际: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
Run Code Online (Sandbox Code Playgroud)
得到:
<console>:14: error: type mismatch;
found : Array[Byte]
required: String
"foo".getBytes + "bar".getBytes
^
Run Code Online (Sandbox Code Playgroud)
因为这种Predef转变.在你之后import MyStuff.ByteArrayOps,它有效.
| 归档时间: |
|
| 查看次数: |
2478 次 |
| 最近记录: |