使用隐式在Scala中创建字节文字

时间:2019-04-18 04:49:59

标签: scala implicit

我正在尝试使用隐式类在scala中创建字节文字。但是,我发现很难理解为什么这不起作用

此处fixed.get()返回字节

implicit class ByteContext(private val sc: StringContext) {
      def hex(args: Any*): Byte = {
        val parts = sc.parts.toList
        assert(
          parts.size == 1 && args.size == 0,
          "Expected a string literal with exactly one part"
        )
        Integer.parseInt(parts(0), 16).toByte
      }
    }

    val aByte = hex"0x4D"
    if ((fixed.get() ne aByte) || (fixed.get() ne aByte)) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")

这是我遇到的错误

Error:(49, 25) the result type of an implicit conversion must be more specific than AnyRef
    if ((fixed.get() ne aByte) || (fixed.get() ne aByte)) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")
Error:(49, 25) type mismatch;
 found   : Byte
 required: AnyRef
    if ((fixed.get() ne aByte) || (fixed.get() ne aByte)) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")
Error:(49, 51) the result type of an implicit conversion must be more specific than AnyRef
    if ((fixed.get() ne aByte) || (fixed.get() ne aByte)) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")
Error:(49, 51) type mismatch;
 found   : Byte
 required: AnyRef
    if ((fixed.get() ne aByte) || (fixed.get() ne aByte)) throw new IllegalArgumentException("Magic of ciphertext number doesn't match")

1 个答案:

答案 0 :(得分:2)

错误与ByteContext隐式转换无关。

42 ne 43  
//Error: the result type of an implicit conversion must be more specific than AnyRef

neAnyRef类中的方法,用于测试A是否是对B的引用。但是您的Byte值不是引用。编译器告诉您,不允许将它们转换为期望的类型AnyRef

顺便说一句,java.lang.Byte.valueOf(parts(0),16)可能是更直接的StringByte转换。