Создание байтовых литералов в scala с использованием имплицитов - PullRequest
1 голос
/ 18 апреля 2019

Я пытаюсь создать байтовый литерал в 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 Ответ

2 голосов
/ 18 апреля 2019

Ошибка не в неявном преобразовании ByteContext.

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

ne - это метод в классе AnyRef, используемый для проверки того, является ли A ссылкой на B. Является ли она / нет, но ваши значения Byte не являются ссылками. Компилятор сообщает вам, что преобразование их в ожидаемый тип AnyRef недопустимо.

Кстати, java.lang.Byte.valueOf(parts(0),16), вероятно, является более прямым преобразованием String в Byte.

...