Scala泛型类支持多参数功能 [英] Scala generic class supporting function of multiple arities

查看:46
本文介绍了Scala泛型类支持多参数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 Foo 类,它支持使用元组技巧的任何数量的函数:

Suppose I have the following class Foo, that supports a function of any arity using the tupling trick:

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

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

I can define a subclass with the following syntax:

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)

这很笨拙.理想的语法如下:

This is pretty clunky. The ideal syntax would be as follows:

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

有什么方法可以定义我的基类以实现这一目标?

Is there any way to define my base class such that this can be achieved?

推荐答案

如果您可以将实现定义为函数而不是方法,那么这很有效:

If you can be satisfied with defining the implementation as a function rather than a method, then this works:

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

class Moo extends Foo[(Int, 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
}

否则,我认为您将需要更多机制来支持不同数量的实现方法签名:

Otherwise, I think you'll need more machinery to support implementation method signatures for different arities:

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

trait FooImpl2[T1, T2, 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
}

这篇关于Scala泛型类支持多参数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆