简体   繁体   中英

Structural type in function with generic type parameter

While experimenting in Scala, I frequently find myself wanting to define a function for all types that define foo . I can do this with Structural Typing for simple cases, but it falls apart when a type parameter is required.

Here's a trivial example:

def reverse[A](xs: { def reverse(): A }): A = xs.reverse

This compiles without error, but fails upon passing a type that defines a reverse function, with the following error:

scala> reverse("string")
<console>:13: error: type mismatch;
 found   : String("adsf")
 required: AnyRef{def reverse(): ?}
              reverse("adsf")
                      ^

I've also tried defining the structural bound on the type parameter, [A <: { def reverse(): A }] , but get the same sorts of results. It looks like I may be the victim of type erasure here (seeing as it expects the result of reverse to be ? ).

I'm not sure if this kind of type constraint is impossible in Scala's type system, or if I'm missing something. Is there some way to define a structural type for a function that has a generic parameter?


Note: I briefly considered that my problem in the given example was that reverse is actually defined on StringOps , not string. Unfortunatelly, wrapping my string in a StringOps container exhibits the same problems.

This works for me:

def getReverse[A](xs: {def reverse: A}): A = xs.reverse

scala> getReverse("1234")
res10: scala.collection.immutable.WrappedString = 4321

Apparently defining reverse in the structural type without parentheses works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM