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

Scala泛型类支持多个arities的功能

发布时间:2020-12-16 10:01:44 所属栏目:安全 来源:网络整理
导读:假设我有以下类Foo,它使用tupling技巧支持任何arity的函数: abstract class Foo[T,R] { def pull: T = R} 我可以使用以下语法定义子类: implicit def function2Tofunction1[T1,T2,R](f: (T1,T2) = R): ((T1,T2)) = R = { f.tupled }class Moo extends Foo[
假设我有以下类Foo,它使用tupling技巧支持任何arity的函数:

abstract class Foo[T,R] {
  def pull: T => R
}

我可以使用以下语法定义子类:

implicit def function2Tofunction1[T1,T2,R](f: (T1,T2) => R): ((T1,T2)) => R = {
    f.tupled 
}

class Moo extends Foo[(Int,Int),Int] {
  def pullImpl(x: Int,y:Int):Int = x + y
  def pull = (pullImpl _) // implicit converts to tupled form
}

val m = new Moo()
m.pull(4,5)

这非常笨重.理想的语法如下:

class Moo extends Foo[(Int,y:Int):Int = x + y
}

有没有办法定义我的基类,这样才能实现?

解决方法

如果您对将实现定义为函数而不是方法感到满意,那么这可以:

abstract class Foo[T,R] {
   type Fn = T => R
   val pull: Fn
}

class Moo extends Foo[(Int,Int] {
   // The type has to be explicit here,or you get an error about
   // an incompatible type. Using a type alias saves typing out
   // the whole type again; i.e. ((Int,Int)) => Int
   lazy val pull: Fn = (x: Int,y: Int) => x + y
}

否则,我认为你需要更多的机器来支持不同arities的实现方法签名:

trait Foo[T,R] { 
   type Fn = T => R
   val pull: T => R
} 

trait FooImpl2[T1,R] extends Foo[(T1,T2),R] {
   lazy val pull: Fn = (pullImpl _).tupled
   protected def pullImpl(x: T1,y: T2): R
}

// similarly for FooImpl3,FooImpl4,...

class Moo extends FooImpl2[Int,Int,Int] {
   protected def pullImpl(x: Int,y: Int) = x + y
}

(编辑:李大同)

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

    推荐文章
      热点阅读