【问题标题】:How to partially apply case class with type parameter in Scala如何在Scala中部分应用带有类型参数的案例类
【发布时间】:2014-06-09 12:04:56
【问题描述】:

所以我有一个元组,我想将它作为 Scala 中案例类的参数传递。对于没有类型参数的案例类,这很容易,我可以这样做:

 scala> case class Foo(a: Int, b: Int)
 defined class Foo

 scala> (Foo.apply _)
 res0: (Int, Int) => Foo = <function2>

 scala> val tuple = (1, 2)
 tuple: (Int, Int) = (1,2)

 scala> res0.tupled(tuple)
 res1: Foo = Foo(1,2)

 scala> Foo.tupled(tuple)
 res2: Foo = Foo(1,2)

但是,如果案例类有类型参数,它似乎不起作用:

scala> (Bar.apply _)
res26: (Nothing, Nothing) => Bar[Nothing] = <function2>

scala> res26.tupled(tuple)
<console>:18: error: type mismatch;
 found   : (Int, Int)
 required: (Nothing, Nothing)
              res26.tupled(tuple)
                           ^
scala> (Bar[Int].apply _)
<console>:16: error: missing arguments for method apply in object Bar;
follow this method with `_' if you want to treat it as a partially applied function
              (Bar[Int].apply _)

scala> Bar.tupled(tuple)
<console>:17: error: value tupled is not a member of object Bar
              Bar.tupled(tuple)
                  ^

scala> Bar[Int].tupled(tuple)
<console>:17: error: missing arguments for method apply in object Bar;
follow this method with `_' if you want to treat it as a partially applied function
              Bar[Int].tupled(tuple)
                 ^

如何部分应用带有类型参数的案例类?我正在使用 Scala 2.10.3。

【问题讨论】:

    标签: scala generics partialfunction


    【解决方案1】:

    这似乎有效:

    scala> case class Foo[X](a:X, b: X)
    defined class Foo
    
    scala> Foo.apply[Int] _
    res1: (Int, Int) => Foo[Int] = <function2>
    
    scala> 
    

    【讨论】:

    • 我没有尝试过的唯一排列:p
    • 要实现的是Foo是一个对象,对象不能有类型参数,只有类和函数可以。
    • 只有类和方法才能有类型参数不是更准确吗?这是我阅读 Shapeless (chuusai.com/2012/04/27/shapeless-polymorphic-function-values-1) 背后的一些文档后的理解
    • 是的,当我说“方法”的“功能”时,我很草率。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2013-06-14
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多