Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef in Scala

Tags:

scala

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.

like image 999
Aleksandr Pakhomov Avatar asked Jan 19 '14 21:01

Aleksandr Pakhomov


People also ask

How do you define type 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.

What does => mean in Scala?

=> 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 .

What is function type in Scala?

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.

How does Scala determine types when they are not specified?

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.


1 Answers

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 } 
like image 146
yǝsʞǝla Avatar answered Sep 24 '22 12:09

yǝsʞǝla