使用implicits在scala中创建字节文字

问题描述 投票:1回答:1

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

这里fixed.get()返回Byte

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")
scala implicit
1个回答
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转换。

© www.soinside.com 2019 - 2024. All rights reserved.