【问题标题】:how to map implicit class parameter to trait variable?如何将隐式类参数映射到特征变量?
【发布时间】:2014-09-13 11:01:32
【问题描述】:

我在隐式参数和 tratis 方面遇到了有趣的问题。

我有一个抽象类 Parent 隐含地接受一个整数和 2 个其他参数:

abstract class Parent(a: Int)(implicit str: String, map: Map[String,String]) {/*...*/}

还有一个特征 ClassTrait 将与 Parent 混合并使用隐式:

trait ClassTrait {
    val str: String
    val map: Map[String,String]

    def doSth() = str.length
}

所以现在我想做这样的事情(withnout关键字abstract):

class Child(a: Int)(implicit str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
    def doSth2 = doSth * 10
}

我应该使用什么语法来将隐式参数映射到 trait vals?编译器返回此错误:

foo.scala:10: error: class Child needs to be abstract, since:
value map in trait ClassTrait of type Map[String,String] is not defined
value str in trait ClassTrait of type String is not defined
class Child(a: Int)(implicit str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
      ^
one error found

在复杂的例子中,我在 trait 中使用了隐式参数,但由于 trait 不能有任何参数(没有构造函数),我需要再次声明使用的隐式。

感谢您的帮助。

【问题讨论】:

    标签: scala inheritance implicit traits


    【解决方案1】:

    试试

    class Child(a: Int)(implicit val str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
       def doSth2 = doSth * 10
     }
    

    (见我添加的val

    或使用case class。然后它们将成为字段。

    另一种方法可能是不使它们隐式并在伴随对象中使用应用方法,该方法采用隐式来设置它们。但是您仍然需要将它们设为字段,您当前的代码在技术上只是将它们视为构造函数参数。

    【讨论】:

      【解决方案2】:

      您可以使用 val 关键字将类参数提升为字段:

      abstract class Parent(a: Int)(implicit val str: String, val map: Map[String,String]) {/*...*/}
      

      注意“val str”和“val map”,而不仅仅是“str”和“map”。这样,它们将成为正确的只读成员,并为您的 trait 的抽象成员提供实现。

      【讨论】:

      • 我回答明显比你早 3 秒!!哈哈:)
      猜你喜欢
      • 2016-07-07
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2021-08-29
      • 2011-06-01
      相关资源
      最近更新 更多