给定一个案例类,我想检索应用方法。
我可以做 A.apply _
但有没有办法只用 A 检索它
例子
scala> case class A(s: String)
defined class A
scala> def f[B, C](h: B => C) = h
f: [B, C](h: B => C)B => C
scala> f(A.apply _)
res0: String => A = <function1>
是否可以只写 f(A)
或类似的东西
最佳答案
以下在 Scala 2.11 中对我有用:
package sandbox
object ApplyMethod {
import sandbox.OtherApplyTest.C
case class A(s: String)
object B {
def apply(s: String): A = A(s)
}
def D(s: String) = OtherApplyTest.D(s)
def f[T](h: String => T) = h("hello")
def g[T, U](h: T => U) = h
def main(args: Array[String]) {
println(f(A)) // prints A(hello)
// println(f(B)) doesn't compile
println(f(C)) // prints C(hello)
println(f(D)) // prints D(hello)
println(g(A)) // prints A
println(g(C)) // prints C
println(g(D)) // prints <function1>
println(f(g(A))) // prints A(hello)
}
}
object OtherApplyTest {
case class C(s: String)
case class D(s: String)
}
看起来你想做什么(以及你是怎么做的)可能是它在 REPL 或旧的 Scala 版本中不起作用。
关于scala - 如何检索案例类的应用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288186/