Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Scala strongly typed ? [closed]

  1. Is Scala strongly typed ? Do you have example how is it being reflected in the language type system? Does Scala allow type punning? Does it allow coercion?

  2. Does Scala have polytypes like ML?

Thank you!

like image 866
Gal peretz Avatar asked Jun 01 '15 13:06

Gal peretz


People also ask

Is Scala a strongly typed language?

Scala is strongly statically typed, but it additionally stands out amongst other statically typed languages as having a particularly advanced advanced type system.

What is the most strongly typed language?

Smalltalk, Ruby, Python, and Self are all "strongly typed" in the sense that typing errors are prevented at runtime and they do little implicit type conversion, but these languages make no use of static type checking: the compiler does not check or enforce type constraint rules.

Is C++ strongly or weakly typed?

The C++ programming language is considered strongly typed and has parametric polymorphism available through templates. This means you can create a set of generic data types and accurately represent them.


1 Answers

  1. Yes.

Because of strong typing, it does not allow "type punning" as I understand it is used in the C language. However, you have sub-typing, therefore you can safely use a value of type A where a value of type B is requested, if A <: B (A is a sub-type of or more specific than B).

You can coerce a type using a.asInstanceOf[B], however this will be type-checked at runtime and causes an exception to be thrown if a is not a sub-type of B, with the exception of higher-kinded types which are erased on the JVM, meaning that such an exception may be thrown only later when actual values of the type parameters are referenced.

Another exception is structural typing which could be thought of as a "punning", although type-safe:

// ordinary type
trait Foo {
  def bar: Int
}

 // structural type
type Bar = Any {
  def bar: Int
}

def test(b: Bar) = b.bar

test(new Foo { val bar = 1234 })  // allowed

This is considered an advanced feature that is rarely used and may even be deprecated in future Scala versions. It requires runtime reflection and thus comes with a performance penalty.

You may also abandon the static type system using the special Dynamic trait. Or you may do crazy stuff using macros to implement your own sort of punning.

  1. No idea, not an ML expert. But if polytype just means this, then this looks like ordinary higher-kinded (parametrised) types or "generics", and the answer would be Yes.

    • Example: the identity function: def identity[A](x: A): A = x
    • Example: single type parameter: trait Option[+A] { def get: A }
like image 113
0__ Avatar answered Sep 29 '22 20:09

0__