How to use nested generics in scala -
edit simplified example. added more detail.
what i'd compose class method. class has type parameter of form a[b], , b abstract types (generic parameters), , methods can work objects of types or b, or other types composed or b. example, class might have method takes a[b] type object parameter, , return b type object.
this kind of pattern extremely common in say, c++ standard template library.
is possible in scala?
in example below, within listdoer, abstract type name listt , b abstract typename telement. later, try provide concrete types, listt[telement] = mylist[double]
class listdoer[ listt[telement] ] { // processes abstract list type. def doit( list:listt[telement] ) : telement = { list.get(0) } // telement not found // attempt 2: type l=listt[telement] // telement not found def doit2( list:l ) : telement ={ list.get(0) } // telement not found } // more concrete list type class mylist[telement] { var none: telement = _ def get(i:int): telement = none // placeholder def put(i:int, value:telement): unit = { } } // mylist[double] concrete list type doit should take parameter val doer2 = new listdoer[ mylist[double] ] // mylist[double] takes no parameters, expected 1 val list1 = new mylist[double] doer2.doit( list1 ) // process list1. should return list1.get(0)
list.get(0) placeholder implementation example.
listdoer class should not require any external types other provided type parameters. (e.g. should not tied particular implementation of list, or interfaces specified in particular collections library). however, above code going require listt[elementt] has method: get(int):elementt , cause listdoer fail instantiated not met.
the above code looks reasonable me (coming c++ background), fails compile in 2 places:
scala can't see name telement anywhere within listdoer. make hard make methods takes or returns telement
the listdoer cannot instantiated
it kind of nested use of generics permitted in scala?
object xxx { class mylist[t] { var none: t = _ def get(k: int): t = none // placeholder def put(k: int, v: t): unit = {} } class listdoer[t] { // defines "wrapper" type // requires method there type w[t] = { def get(k: int): t } def doit(list: w[t]): t = { return null.asinstanceof[t] } } type l = double val doer1 = new listdoer[l] // l takes no parameters, expected 1 val doer2 = new listdoer[double] // l takes no parameters, expected 1 val list1 = new mylist[double] val list2 = list[l]() doer1.doit(list1) }
Comments
Post a Comment