reset password
Author Message
mnava18
Posts: 86
Posted 21:15 Oct 13, 2014 |

im having  some problems trying to understand what type is and when to use it. i read the previous post and understood type to be an alias. so how is this different from just using def? if you didnt tell us to use type when we made set , i would went with def.

Adam Berman
Posts: 19
Posted 13:46 Oct 14, 2014 |

Let's compare the following:

type Set = Int => Boolean

def Set: (Int => Boolean) = (x:Int) => x > 5

The first is sort of like an abstract class in Java; it says "A 'Set' is a type you can instantiate, and it can be any relation from an Integer to a Boolean."

The second says "Set is a relationship from an Integer to a Boolean (def Set: (Int => Boolean)) and the relation is that if the Integer is greater than Five the Boolean is true, otherwise it is false. (= (x:Int) => x > 5)"

 

types are aliases for the types that functions input and output. Integer, Boolean, Double, String, Char are all types. Note that they hold no data themselves; they merely describe the format of data. defs, on the other hand, define static data which is substituted wherever the alias appears in the code.

 

From a text-processing perspective they work very, very similarly. The difference, if it helps you to think of it this way, is that types are conceptual and defs are concrete; types describe what kind of information objects (or arguments) can hold; defs describe specific instances of data.

 

Note that this would be a valid Set according to the first type statement:

def ExampleSet(str:String): Set = (x:Int) => str.length == x

Types can take input, and can also do whatever processing it wants to do in the backend. For example

def ExSet2(str:String): Set = !ExampleSet(str)

or even

def ExSet3(str:String): Set = singletonset(str.length)

are perfectly legitimate definitions (assuming you defined singletonset and ExampleSet).

 

For comparison, here are some type statements:

type SetEval = Set => Boolean

This says "A SetEval is an object that represents a relation from a Set to a Boolean."

An example of a SetEval would be:

def Ex4: SetEval = (x:Set) => x(0) == true

Ex4 is passed an instantiated set object, and returns true if 0 is in the set. Note that part of the potential confusion here is that parenthetical arguments are used both as part of a constructor (e.g., def foo:Set = ExSet2("bar") ) and to pass values to the relation (as we did here). I don't have a great answer as to why scala doesn't have two different ways to do this, to reduce this confusion.

Last edited by Adam Berman at 14:25 Oct 14, 2014.