Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare a type alias in a scala constructor?

If I have a class that takes a tuple in its constructor among other values such as:

class Foo(a: Int, b: String, c: (Int, String)) 

How do I use an abstract type to give the tuple a more descriptive name in a lightweight fashion (without wrapping it in a new class):

class Foo(a: Int, b: String, c: Dave) 

I'm not sure how to bring a type alias in scope (or if this is the best thing to do):

type Dave = (Int, String) 

Is there a convention for where to define types in this way (or should I be defining case classes and wrapping everything...)?

I appreciate that it does not make sense in a lot of situations but if I'm really only looking for a more descriptive name is it possible?

Thanks!

like image 629
Matthew Pickering Avatar asked Mar 21 '12 10:03

Matthew Pickering


People also ask

What is type alias in Scala?

A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.

What is type constructor in Scala?

You can use certain types (like Int or String ) using literals ( 1 or 2 for Int or "James" for String ). Type constructors are types that need other types to be built. List or Option won't be a fully qualified type unless you pass another type to them (i.e. List[Int] or Option[String] – mfirry.

What are type aliases?

Type aliases Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead.

What is type alias in Elm?

A type alias is a shorter name for a type. For example, you could create a User alias like this: type alias User = { name : String , age : Int } Rather than writing the whole record type all the time, we can just say User instead.


1 Answers

You could use a type alias like:

scala> type MyTuple = Tuple2[Int,String]
defined type alias MyTuple

scala> val x = new MyTuple(1, "one")
x: (Int, String) = (1,one)
like image 137
jxstanford Avatar answered Nov 10 '22 09:11

jxstanford