我有很多方法如下
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)
}
有没有办法在Scala中推广这些方法?有什么建议吗?
答案 0 :(得分:3)
不太确定“概括”是什么意思。这样的事可能吗?
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"
答案 1 :(得分:0)
也许将它们分组:
def functions (param1: String, param2: Int) = new {
def one: ReturnTypeOne = ???
def two: ReturnTypeTwo = ???
def n: ReturnTypeN = ???
}
...
functions("a", 4).one
functions("b", 7).two