2014-10-09 31 views
3

給定一個案例類,我想要檢索apply方法。如何檢索案例類的申請方法

我能做的A.apply _但有沒有辦法只能用一個

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)或類似的

回答

3

下對我的作品在斯卡拉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版本。

2

我以前從來沒有的東西遇到Scala認爲A(...)A.apply(...)不同的情況。在我的翻譯,f(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) 
res1: String => A = A