Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we have a dynamically typed language over JVM?

We have Jython, JRuby, Groovy which are dynamically typed and runs over JVM. I understand that these languages compile to bytecode.

Other languages such as Scala supports type inference, and its clear that the compiler infers the type for us.

But Java is a static language and it compiles to bytecode, does this mean bytecode supports dynamic typing?

For e.g. In Java we need to declare the variable type at compile time, and can never change it. But in case of Python we dont have to declare a type, but we can assign any type of value to the same variable during run time.

How does the dynamic typing work over a static language?

like image 415
18bytes Avatar asked Jul 10 '12 05:07

18bytes


1 Answers

But Java is a static language and it compiles to bytecode, does this mean bytecode supports dynamic typing?

Yes it does mean that.

You see Java is not a completely statically typed language. Whenever you cast an object from a type to a subtype, the JVM performs a dynamic (runtime) typecheck to check that the object really is an instance of the subtype. Using instanceof is another example of dynamic type checking.

Dynamic type checking is also used under the covers when you use the reflection APIs, and even when you use generics.

How does the dynamic typing work over a static language?

If it is a purely statically type-checked language then it doesn't. For instance, Pascal is a strongly typed language with (purely) static typing. But most modern programming languages support at least some level of runtime type checking. And many dynamically typed languages have either optional static typing, or developer tools that use type inferencing to pick up type-related errors.

Incidentally, a language can be both statically typed and use type inferencing. Type inference should be viewed as an alternative to explicit type declarations, not an as alternative to static typing.

like image 147
Stephen C Avatar answered Sep 27 '22 18:09

Stephen C