In Scala, can generic type parameters be used with *function* definitions?

后端 未结 4 1444
Happy的楠姐
Happy的楠姐 2020-12-25 15:02

Is there a syntax to allow generic type parameters on function literals? I know I could wrap it in a method such as:

def createLongStringFunction[T](): (T) =         


        
4条回答
  •  没有蜡笔的小新
    2020-12-25 15:57

    No, type parameters only apply to methods and not function objects. For example,

    def f[T](x: T) = x     //> f: [T](x: T)T
    val g = f _            //> g: Nothing => Nothing = 
    // g(2)                // error
    val h: Int=>Int = f _  //> h  : Int => Int = 
    h(2)                   //> res0: Int = 2
    

    The method f cannot be converted to a polymorphic function object g. As you can see, the inferred type of g is actually Function1[Nothing, Nothing], which is useless. However, with a type hint we can construct h: Function1[Int,Int] that works as expected for Int argument.

提交回复
热议问题