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

scala – 如何使用具有通用参数的结构类型?

发布时间:2020-12-16 19:10:10 所属栏目:安全 来源:网络整理
导读:我有两个案例类 case class StringCaseClass(argument: String)case class IntCaseClass(argument: Int) 我想定义一个结构类型,它将匹配这两个的伴随对象 type HasApply1 { def apply[A,R](argument: A): R} 这将编译正常,但当我尝试使用它这样 def method(c
我有两个案例类

case class StringCaseClass(argument: String)

case class IntCaseClass(argument: Int)

我想定义一个结构类型,它将匹配这两个的伴随对象

type HasApply1 {
  def apply[A,R](argument: A): R
}

这将编译正常,但当我尝试使用它这样

def method(caseClass: HasApply1) {
  // whatever
}

method(StringCaseClass)

我会得到一个编译器错误

found   : StringCaseClass.type
required: WithApply1
            (which expands to)  AnyRef{def apply[A,R](string: A): R}

有没有办法实现这个?如果我重新定义结构类型以具有A和R的具体类型,它将正确编译,但后来我失去了灵活性

解决方法

@ aloiscochard的评论几乎就在那里.他忘了提到的是,case类的伴随对象已经实现了相应的FunctionN特性,所以你可以简单地这样做,

scala> case class StringCaseClass(argument: String)
defined class StringCaseClass

scala> case class IntCaseClass(argument: Int)
defined class IntCaseClass

scala> def method[A,R](caseClass: A => R,a: A) = caseClass(a)
method: [A,a: A)R

scala> method(StringCaseClass,"foo")
res0: StringCaseClass = StringCaseClass(foo)

scala> method(IntCaseClass,23)
res1: IntCaseClass = IntCaseClass(23)

(编辑:李大同)

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

    推荐文章
      热点阅读