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

后端 未结 4 1442
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:55

    Since longStringFunction defined as followed is a value, which must have some given type.

    val longStringFunction: (T) => Boolean = (obj: T) => obj.toString.length > 7
    

    However, you can reuse a function object with a method:

    scala> val funObj: Any => Boolean = _.toString.size > 7
    funObj: Any => Boolean = 
    
    scala> def typedFunction[T]: T => Boolean = funObj
    typedFunction: [T]=> T => Boolean
    
    scala> val f1 = typedFunction[String]
    f1: String => Boolean = 
    
    scala> val f2 = typedFunction[Int]
    f2: Int => Boolean = 
    
    scala> f1 eq f2
    res0: Boolean = true
    

    This works because trait Function1[-T1, +R] is contravariant of type T1.

提交回复
热议问题