score:29
The keyword type
in Scala creates an alias for a given type. For example:
scala> type Str = String
defined type alias Str
scala> val greeting: Str = "Hello World!"
greeting: Str = Hello World!
This is very similar to what you did:
scala> type Set = Int => Boolean
defined type alias Set
scala> val isEven: Set = _ % 2 == 0
isEven: Int => Boolean = <function1>
scala> println(isEven(4))
true
scala> println(isEven(5))
false
Although type aliases may sometimes be useful for clarification purposes, documentation is not their primary use case. Scala's type system is very sophisticated. For instance there is an alternative to generics, namely abstract types. Consider this:
// Generics
abstract class GenericAbstraction[TypeArgument]
class GenericConcrete extends GenericAbstraction[String]
// Abstract types
abstract class TypeAbstraction {
type TypeArgument
}
class TypeConcrete extends TypeAbstraction {
type TypeArgument = String
}
These code samples basically accomplish the same thing, but there are situations where you need abstract types, but can't (or shouldn't) use generics. You can find more information here.
score:0
I am considering like this. The function definition in the type is abstract, which makes it possible to define different concrete methods to implement them. I think it is called Polymorphism or later binding. which makes it possible to bind the function type and concrete method later in the runtime.
I think in JAVA, you cannot override an abstract method by static method. But in functional language, it seems very naturally to define concrete method to implement the abstract function. Please correct me if I am wrong.
Look at this about "polymorphic-functions".
http://gleichmann.wordpress.com/2011/01/23/functional-java-polymorphic-functions/
But the conclusion is sad to me. We can only simulate it in scala. Check this from the link.
"Wow, what a journey. We saw that it’s not possible to directly define polymorphic functions in Scala. Instead there are some work arounds to kind of simulating them. It all comes down to the fact, that a function is a value of a certain Function type, which needs to be type parameterized at runtime, that is all type parameters need to be type parameterized for getting a real value (or instance of that type)."
"So as a last conclusion, defining polymorphic functions is possible, but the consequences might outweight the benefits. As always, you need to be aware of the given risks and decide for yourself if it’s worth the trade offs (which i hope to have shown to you) for your concrete problem area …"
score:1
You can define a function literal as follows:
val incrementor = (x: Int) => x + 1
or if you have some context that can be used by Scala's type inference, you can use reduced forms like:
val listOfInt = List(1, 2, 3, 4, 5)
listOfInt map {x => x + 1}
listOfInt map {_ + 1}
or even
listOfInt map {1 +}
These literals all imply the type themselves or have their type constrained by the expected type of a higher order function they are being passed to.
There have been several questions on SO about the difference between functions and methods which would be good background reading but perhaps taking a look at the free version of Martin Odersky's book Programming in Scala (Version 1) would be a much better starting point to read up about functions and methods.
Source: stackoverflow.com
Related Query
- How to use the function type in scala within defined in type meaningfully?
- How do I know the type of a scala function
- How to cast Scala value already defined in the function
- In scala 2.11+ how to use exactly the singleton type as type evidence?
- In Scala how do I define upper type bounds that are exclusive of the defined class?
- How to use attribute names if the table has more than 22 columns so it is defined as a type. Slick / Scala
- How execution of same function defined with "_" is different from the same defined with a named variable in Scala
- How to use the OR operator within a filter predicate when using _._2 in scala
- Scala : Force the type of some function to use the type of this in a trait
- How can I use Scala reflection to find the self type traits?
- How to get the class of a trait within an object defined in scala from within a java class?
- Scala classOf for type parameter: how to call the function and how to restrict with upper type bounds
- In scala how do you enforce the encoder to operate on the type when gets inserted into a generic function that only enforces certain traits?
- How to use a Scala sub-class constructor for a member within the super-class?
- How do I view the type of a scala expression in IntelliJ
- How do I get the Scala version from within Scala itself?
- Scala type keyword: how best to use it across multiple classes
- How the get the classOf for a scala object type
- How are Scala collections able to return the correct collection type from a map operation?
- Should I use Unit or leave out the return type for my scala method?
- How to use / refer to the negation of a boolean function in Scala?
- What special rules does the scala compiler have for the unit type within the type system
- How to define a function whose output type depends on the input type
- How to run an external file from within the scala interactive interpreter (REPL)?
- Why does this Scala function compile when the argument does not conform to the type constraint?
- How to use Type calculated in Scala Macro in a reify clause?
- How to use Scala Cats Validated the correct way?
- How to mock a function within Scala object using Mockito?
- Scala spark: how to use dataset for a case class with the schema has snake_case?
- How can I write a function have a polymorphic return type based on the type argument of its type parameter?
More Query from same tag
- Scala/Java Project not finding Dependencies during Maven compile
- Is there a way to expand the scope of an existential type quantifier in Scala to convince the type checker that two variables have the same type?
- Scala formatting Array.mkString
- No Json serializer as JsObject found for type play.api.libs.json.JsObject. Try to implement an implicit OWrites or OFormat for this type
- SBT: How to trigger separate actions when files change in two separate subprojects
- Why are Map and Set aliased in scala.Predef?
- Squeryl: Typed Primary keys
- Dataframe for textfile Spark
- Composing a list of pairs
- How can I create a typed Tuple2 from Java / Spring?
- Dyamically cast spark dataframe to dataset of tuple(String,_<:Product)
- Functional style early exit from depth-first recursion
- HBase dependencies with SBT in Scala
- Why do I need an explicit type argument list here?
- sbt docbook plugin
- scala swing performance depends on events?
- Accessing class field in foreach Generics Scala
- How are Akka messages ordered if messages are not reliable?
- Per-Document Word Count in Spark
- Update Spark Dataframe's window function row_number column for Delta Data
- How to pattern match int strings?
- What languages are mature to develop native apps in Android [except Java]
- part of string value in black list array spark dataframe
- Scala: Find and update one element in a list
- scala object modules is not a member of package play
- Why Feedly API did not return ALL ids entries in stream of category?
- Scala - encapsulating data in objects
- Pattern matching is not giving the expected results
- package compatability between Scala 2.10 and 2.11
- Ignoring fields with Jerkson Parsing, expected a valid value error