Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in scala define generic type based on duck typing?

I understand I can define duck typing in generics as following

trait MyTrait[A <: {def someMethod(key: String): String}]

However I don't want to specify that whole big string in my trait definition.

How can I split this to two (what I wish I could have):

type A = B <: {def someMethod(key: String): String}

trait MyTrait[A]
like image 744
Jas Avatar asked Mar 31 '15 12:03

Jas


1 Answers

You can do:

type B = { def someMethod(key: String): String }
trait MyTrait[A <: B]

In fact, some Scala style guides recommend this breakdown when the structural type would have more than 50 characters. Here's one from the Scala docs:

Structural types should be declared on a single line if they are less than 50 characters in length. Otherwise, they should be split across multiple lines and (usually) assigned to their own type alias

You cannot assign the type bound A <: B itself to a type alias, since it is not a type, but a constraint on the generic parameter of MyTrait. You can read more about type bounds here.

like image 74
Ben Reich Avatar answered Oct 22 '22 10:10

Ben Reich