Is Scala strongly typed ? [closed]
Asked Answered
W

1

6
  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!

Wadai answered 1/6, 2015 at 13:1 Comment(2)
you'll end up in a hornets nest here because weak or strong typing is not really well-defined (says Wikipedia) ;)Cystolith
This question cannot be answered until you give a precise definition of "strongly typed".Ninetieth
E
7
  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 }
Erewhile answered 1/6, 2015 at 13:22 Comment(2)
But what about "1.0" + 5, scala converts 5 to string and result is "1.05". Scala behaves like a weakly typed language here.Hairpiece
A better way to check is to apply 1 == "1" which will return false for strongly typed languages, which don't do coercionBalcke

© 2022 - 2024 — McMap. All rights reserved.