通用方法的scala覆盖特征 [英] scala override trait with generic method

查看:93
本文介绍了通用方法的scala覆盖特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个类:

  class AClass 
class Base {val a =a}
class BaseOne extends Base {val b =b}
class BaseTwo extends Base {val c =c}

我想扩展一个包含泛型方法的特性,我不允许改变特性

< pre $ $ $ $ $ $ def fromAClass [T< base](s: AClass):T
}

我想将它扩展到几个不同的对象中

  object ConverterBaseOne extends Converter {
//错误
覆盖def toAClass(e:BaseOne):AClass = {printf (eb)} // b已知
覆盖自fromAlcass(a:AClass)的def:BaseTwo = {....}
}

我知道有一种方法可以通过类参数来实现:trait Converter [T< base]
并且还看到了这个帖子https://stackoverflow.com/a/4627144/980275
我问是否有解决方案,而不改变特质?
谢谢

解决方案

您正在更改方法的签名,因此它不是合法的重写,它会打破多态性。您必须参数化 Converter trait或使用另一个方法名称。



然而,您可以收到 Base 对象并进行强制转换,但不建议练习,因为它可能会在运行时导致异常:

 printf(e.asInstanceOf [BaseOne] .b) 
// ...
}
}


I have 3 classes:

class AClass 
class Base { val a = "a" }
class BaseOne extends Base { val b = "b" }
class BaseTwo extends Base { val c = "c" }

I want to extend a trait which contains a generic method, I'm not allowed to change the trait

trait Converter {
    def toAClass[T <: Base](e: T): AClass
    def fromAClass[T <: Base](s: AClass): T
}

I want to extend it in several different objects

 object ConverterBaseOne extends Converter { 
 // ERROR
     override def toAClass(e: BaseOne) : AClass = { printf(e.b) } // b is known
     override def fromAlcass(a: AClass) : BaseTwo = {....}
 }

I know there is a way to do it with class parameter: trait Converter[T <: Base] and also saw this post https://stackoverflow.com/a/4627144/980275 I'm asking if there is a solution without changing the trait ??? Thank you

解决方案

You are changing the signature of the method, so it is not a legal override, it would break polymorphism. You must either parametrize the Converter trait or use another method name.

You can, however, receive a Base object and cast it, but it is not recommended practice since it may result in an exception at runtime:

object ConverterBaseOne extends Converter { 
  override def toAClass[T <: Base](e: T): AClass = {
    printf(e.asInstanceOf[BaseOne].b)
    // ...
  }
}

这篇关于通用方法的scala覆盖特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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