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

后端 未结 4 1443
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 16:02

    As you say, in your example all you're requiring is the toString method and so Any would be the usual solution. However, there is call for being able to use higher-rank types in situations such as applying a type constructor such as List to every element in a tuple.

    As the other answers have mentioned, there's no direct support for this, but there's a relatively nice way to encode it:

    trait ~>[A[_],B[_]] {
      def apply[X](a : A[X]) : B[X]
    }
    
    type Id[A] = A //necessary hack
    
    object newList extends (Id ~> List) {
      def apply[X](a : Id[X]) = List(a)
    }
    
    def tupleize[A,B, F[_]](f : Id ~> F, a : A, b : B) = (f(a), f(b))
    
    tupleize(newList, 1, "Hello") // (List(1), List(Hello))
    

提交回复
热议问题