How can I define type in Scala? Like
type MySparseVector = [(Int, Double)]
in Haskell or
typedef MySparseVector = std::list<std::pair(int, double)>>
in C++?
I tried
type MySparseVector = List((Int, Double))
but can't figure how to make it work. If I write this in the beginning of class file I got "Expected class or object definition" error.
PS Sorry, I mistyped. I tried to use List[(Int, Double)] in Scala.
Scala is a statically typed programming language. This means the compiler determines the type of a variable at compile time. Type declaration is a Scala feature that enables us to declare our own types.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Here, Scala function is first-class value. Scala also has methods, but these differ only slightly from Scala function. A method belongs to a class; it has a name, a signature, [optionally, ] some annotations, and some bytecode. A function is a complete object that we can store in a variable.
Non-value types capture properties of identifiers that are not values. For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type.
type MySparseVector = List[(Int, Double)]
Example usage:
val l: MySparseVector = List((1, 1.1), (2, 2.2))
Types have to be defined inside of a class or an object. You can import them afterwards. You can also define them within a package object - no import is required in the same package, and you can still import them into other packages. Example:
// file: mypackage.scala package object mypackage { type MySparseVector = List[(Int, Double)] } //in the same directory: package mypackage // no import required class Something { val l: MySparseVector = Nil } // in some other directory and package: package otherpackage import mypackage._ class SomethingElse { val l: MySparseVector = Nil }
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