加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

通过给定的通用类型Scala获取类的配对对象

发布时间:2020-12-16 09:41:25 所属栏目:安全 来源:网络整理
导读:我想要做的是制作一个通用类并使用静态方法的函数(对于Java语言,我的意思是它的伴随对象的方法)。 trait Worker {def doSth: Unit}class Baseobject Base extends Worker// this actually wouldn't work,just to show what I'm trying to achievedef callSt
我想要做的是制作一个通用类并使用静态方法的函数(对于Java语言,我的意思是它的伴随对象的方法)。

trait Worker {def doSth: Unit}

class Base

object Base extends Worker

// this actually wouldn't work,just to show what I'm trying to achieve
def callSthStatic[T that companion object is <: Worker](implicit m: Manifest[T]) {
  // here I want to call T.doSth (on T object)
  m.getMagicallyCompanionObject.doSth
}

有任何想法吗?

解决方法

A gist by Miles Sabin可能会给你一个提示:

trait Companion[T] {
  type C
  def apply() : C
}

object Companion {
  implicit def companion[T](implicit comp : Companion[T]) = comp()
}

object TestCompanion {
  trait Foo

  object Foo {
    def bar = "wibble"

    // Per-companion boilerplate for access via implicit resolution
    implicit def companion = new Companion[Foo] {
      type C = Foo.type
      def apply() = Foo
    }
  }

  import Companion._

  val fc = companion[Foo]  // Type is Foo.type
  val s = fc.bar           // bar is accessible
}

如果使用Scala 2.9.x,则应使用-Ydependent-method-types标志编译。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读