实现Ordered [A [B]]的Scala泛型给出了奇怪的编译器错误 [英] Scala generics implementing Ordered[A[B]] gives strange compiler errors

查看:110
本文介绍了实现Ordered [A [B]]的Scala泛型给出了奇怪的编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有奇怪的错误信息,而且我无法用 asInstanceOf [T]

I have strange error message, and I cannot fix it with asInstanceOf[T]

 trait ABase {
    type A <: ABase
    def compare(that: A): Int
  }

  case class B [A <: ABase] (someField: A) {
    //extends Ordered[B[A]] {
    def compare1(that: B [A]): Int = someField.asInstanceOf[A].compare(that.someField.asInstanceOf[A])
    /*Error: type mismatch;
 found   : A
 required: _1.A where val _1: A
    = someField.asInstanceOf[A].compare(that.someField.asInstanceOf[A])*/
    def compare2(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[A])
    /*Error: type mismatch;
 found   : A
 required: B.this.someField.A
    = someField.compare(that.someField.asInstanceOf[A])*/
    def compare3(that: B [A]): Int = someField.compare(that.someField)
    /*Error: type mismatch;
 found   : that.someField.type (with underlying type A)
 required: B.this.someField.A
    = someField.compare(that.someField)*/
  }

错误本身

Error itself


错误:类型不匹配;
found:A
required:_1.A where val _1:A

Error: type mismatch; found : A required: _1.A where val _1: A


推荐答案

您可以通过将其转换为B(this) someField 类型来修复它:

You can fix it by casting to B's (this) someField type:

trait ABase {
  type A <: ABase
  def compare(that: A): Int
}

case class B [A <: ABase] (someField: A) {

  def compare1(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[this.someField.A])

  def compare2(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[this.someField.A])

  def compare3(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[this.someField.A])
}

您还可以保留一个type属性以使其更加简洁:

You can also keep a type attribute to make it more concise:

case class B [A <: ABase] (someField: A) {

  type ThisA = this.someField.A

  def compare1(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[ThisA])

  def compare2(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[ThisA])

  def compare3(that: B [A]): Int = someField.compare(that.someField.asInstanceOf[ThisA])
}

这篇关于实现Ordered [A [B]]的Scala泛型给出了奇怪的编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆