【问题标题】:scala implicit class: inherit all members of parameterscala隐式类:继承参数的所有成员
【发布时间】:2015-12-04 20:59:40
【问题描述】:

我有这个非常有用的隐式类,我想扩展GenIterable

  import scala.collection.GenIterable
  implicit class WhatUpTho[S<:GenIterable[T],T](s:S) extends GenIterable[T]{
    def whatUpTho = println("sup yo")
  }

不幸的是,编译器不允许我写这个,因为它缺少 trait GenIterable 所需的 79 个方法或属性。我想推迟针对WhatUpTho所有 请求,而没有具体定义到它的s 参数。

我该如何做到这一点?

【问题讨论】:

    标签: scala implicit traits


    【解决方案1】:

    没有必要扩展 GenIterable[T]。

    object Conversions {
      implicit class WhatUpTho[S <: GenIterable[_]](s:S) {
        def whatUpTho = println("sup yo")
      }
    }
    
    import Conversions._
    
    val s = List(1, 2, 3)
    s.whatUpTho
    

    关于泛型:

    // Depending on the signature of your functions, you may
    // have to split them into multiple classes.
    object Conversions {
    
      implicit class TypeOfCollectionMatters[S <: GenIterable[_]](s:S) {
        def func1(): S = ...
        def func2(t: S) = ...
      }
    
      implicit class TypeOfElementsMatters[T](s: GenIterable[T]) {
        def func3(): T = ...
        def func4(t: T) = ...
      }
    
       // If you need both, implicit conversions will not work.
      class BothMatters[S <: GenIterable[T], T](s: S) {
        def func5: (T, S) = ...
      }
    }
    
    import Conversions._
    
    val s = List(1, 2, 3)
    s.func1
    s.func2(List(4,5,6))
    s.func3
    s.func4(7)
    
    // You have to do it youself.
    new BothMatters[List[Int], Int](s).func5
    

    【讨论】:

    • 感谢您的洞察力。如果我真的想指定T 怎么办?我还有一些其他更有用的功能,如果他们不知道所有数据类型都相同,它们就不会很好用。尽管有更好的解决方案,但最初的愿望是否可能?
    • 例如:def yoDawgYo = s zip s 产生编译时错误:type mismatch; found : S required: scala.collection.GenIterable[B] 以及其他类似的弯曲。
    • 根据函数的签名,您可能必须将它们拆分为多个类。我用示例代码更新了答案。
    猜你喜欢
    • 2012-02-13
    • 2016-03-12
    • 2010-09-05
    • 2022-10-05
    • 2011-10-10
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多