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!
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With