How to pass type as parameter in scala?

It's very hard for me to try to figure out how to store or pass a type to scala.

What I want to achieve looks something like this:

abstract class Foo( val theType : type ) object Foo{ case object Foo1 extends Foo(String) case object Foo2 extends Foo(Long) } 

So, at some point I can do this:

 theFoo match{ case String => "Is a string" case Long => "Is a long" } 

and upon receipt of an object capable of executing it:

 theFoo.asInstanceOf[Foo1.theType] 

Is it possible? If possible, is this a good approach? What I'm trying to achieve in the long run is to write a pseudo-scheme for processing a stream of bytes. For example, if I have an Array(Foo1,Foo1,Foo2,Foo3,Foo1) scheme Array(Foo1,Foo1,Foo2,Foo3,Foo1) , I can analyze the byte arrays that complain about this scheme, if at some point I have a different byte stream, I could just write new Array(Foo3, Foo4, Foo5) scheme Array(Foo3, Foo4, Foo5) without the need for re-implementing parsing logic.

Hi,


EDIT as requested

Suppose I have Array [Byte] = A973928CB3883FB123 named Command1

The data in these bytes is fixed in position and length. In other words, I know that position 1-4 is, for example, a small date, 5-9 is the name of the customer, etc. Etc.

I want to write one syntax function that takes only a parammeter scheme and returns the actual values ​​of each parameter in the scheme.

 trait Command{ //This is implemented in every command val schema : List[Tuple[String,Int,Int,Type]] //Position,Size,DataType def parse() : List[Tuple[String,Int,Int,Type,Any]] = schema.map(//match using the type) } class Command1 extends Command { override val schema = List[Tuple("theName",0,10,String),Tuple("myType",10,12,MyType),Tuple("theId",13,20,Long)] val theActualName = parse().find(_._1 == "theName")._5.asInstanceOf[String] //I would like to avoid this cast } 

Hope this clarifies what I'm trying to do.

+6
source share
2 answers

You cannot store types in variables. And also you cannot just pass a stream of bytes into a type. You can use a serialization library like protobuf . What is your use case? Where do you get the data from? Is this also a java / scala application? It may be easier for you to help if you say what exactly you want to do.

0
source

You can get types as values ​​with Scala 2.10 (when it comes out). Before that, it is best to choose a class ( classOf[String] , for example), but this loses any type parameter.

Even with Scala 2.10, there are serious limitations that you will encounter. See a recent blog post for an example.

+3
source

Source: https://habr.com/ru/post/924594/


All Articles