简体   繁体   English

通用签名方法

[英]Generalize methods with common signature

I have bunch of methods as follow 我有很多方法如下

def functionOne(param1: String, param2: Int): ReturnTypeOne = {
  doSomethingWith(param1, param2, new ReturnTypeOne)
}

def functionTwo(param1: String, param2: Int): ReturnTypeTwo = {
  doSomethingWith(param1, param2, new ReturnTypeTwo)
}
.....
def functionN(param1: String, param2: Int): ReturnTypeN = {
  doSomethingWith(param1, param2, new ReturnTypeN) 
}

Is there way to generalize these method in Scala? 有没有办法在Scala中推广这些方法? Any suggestion? 有什么建议吗?

Not quite sure what "generalize" means. 不太确定“一般化”是什么意思。 Something like this maybe? 像这样的东西?

trait F[A] {
  def f(x: String, y: Int): A
}

object F {
  def f[A](x: String, y: Int)(implicit ev: F[A]) = ev.f(x, y)

  implicit object FInt extends F[Int] {
    def f(x: String, y: Int) = y
  }

  implicit object FString extends F[String] {
    def f(x: String, y: Int) = x
  }
}

import F._

f[Int]("123", 1) //> 1
f[String]("123", 1) //> "123"

Maybe group them: 也许将它们分组:

def functions (param1: String, param2: Int) = new {
  def one: ReturnTypeOne = ???
  def two: ReturnTypeTwo = ???
  def n: ReturnTypeN = ???
}

...
functions("a", 4).one

functions("b", 7).two

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM