Tipos de datos básicos

6/36

Lectura

Tipos de datos básicos

https://docs.scala-lang.org/tour/unified-types.html#nothing-and-null

Scala tiene una familia de tipos de datos básicos que no son nada diferentes a los que quizás ya conozcas de otros lenguajes. Lo que quizás sí tiene de diferente es cómo se relacionan estos tipos entre ellos.

Como Scala mezcla conceptos de programación orientada a objetos con conceptos de programación funcional, el polimorfismo generado por la herencia de estos tipos de datos puede ser importante en algunas ocasiones, aunque no te afectará para los temas que estaremos tratando a lo largo del curso.

Existe entonces un tipo de dato llamado Any. Debajo de este tendremos otros dos: AnyVal y AnyRef. Este último no nos interesa para esta sección, pero el primero sí, así que vamos a verlo en más detalle.

unified-types-diagram.png

Los tipos que se relacionan con AnyVal son los que solemos llamar tipos de datos básicos, estos son: Double, Float, Long, Int, Short, Byte, Unit, Boolean, y Char.

La mayoría te podrían sonar familiares:

  • Boolean es para almacenar falso o verdadero.
  • Double, Float, Long, Int, Short, son tipos numéricos.
  • Byte se usa para datos binarios.
  • Char se usa para almacenar caracteres/letras.
  • Unit es quizás el tipo extraño acá, este tipo de dato tiene el objetivo de expresar la unidad o también puede entenderse como el vacío. Por ejemplo, en algunos lenguajes se usa una palabra reservada void para expresar esto, pero void no es tratado como un tipo de dato en sí. Usar Unit como un tipo de dato hace el lenguaje más consistente.

Finalmente, tendremos un tipo de dato llamado Nothing, que como su nombre lo indica… es el tipo de dato que usaremos para expresar la nada.

Entonces, así como todos los tipos de datos provienen de Any, o dicho de otra manera, Any es lo que todos los tipos de datos tienen en común, ningún tipo de dato puede provenir de Nothing.

En teoría de lenguajes de programación Nothing es lo que se conoce como bottom type, el tipo de dato más bajo del que ningún otro tipo de dato puede provenir. Any viene siendo el top type, el tipo de dato más alto del que todos los demás provienen.

Si conoces los tipos básicos de Java, te habrás dado cuenta que aunque Scala tiene una relación muy cercana con Java, aquí no hay una diferencia en cuanto a tipos básicos con los demás tipos de datos.

Por ejemplo en Java el tipo int es distinto al tipo Integer. En Scala de hecho, el tipo Int corresponde directamente al tipo Integer de Java. Lo interesante es que el compilador de Scala es inteligente, y sabe en qué momentos debe usar a bajo nivel, un tipo o el otro.

Como ejercicio, investiga más sobre el tipo Unit y el tipo Nothing, haz un listado de los usos que podrías darles. También puedes escribir las dudas que te generen.

En la próxima clase veremos uno de los temas más importantes cuando quieres hacer programación funcional.

Aportes 5

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Les dejo le definición que encontré mas Entendible

Nothing:
Nothing is also a Trait, which has no instances. It is a subset of each of the distinct types. The major motive of this Trait is to supply a return type for the methods which consistently throws an exception i.e, not even a single time returns generally. It is also helpful in providing a type for Nil.
Unit:
The Unit is Scala is analogous to the void in Java, which is utilized as a return type of a functions that is used with a function when the stated function does not returns anything.

Usos de nothing: Es el tipo de resultado para los metodos, los cuales nunca hacen un return normal. Un ejemplo es el metodo Scala.sys, el cual retorna una excepción.

You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: “The reason Scala has a bottom type is tied to its ability to express variance in type parameters.”). From the article you linked to:
One other use of Nothing is as a return type for methods that never return. It makes sense if you think about it. If a method’s return type is Nothing, and there exists absolutely no instance of Nothing, then such a method must never return.

Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.

Type Nothing is at the very bottom of Scala’s class hierarchy; it is a subtype of every other type. However, there exist no values of this type whatsoever. Why does it make sense to have a type without values? One use of Nothing is that it signals abnormal termination. For
instance there’s the error method in the Predef object of Scala’s standard
library, which is defined like this:

def error(message: String): Nothing =
throw new RuntimeException(message)

The return type of error is Nothing, which tells users that the method will not return normally (it throws an exception instead). Because Nothing is a subtype of every other type, you can use methods like error in very flexible ways. For instance:

def divide(x: Int, y: Int): Int =
if (y != 0) x / y
else error(“can’t divide by zero”)

The “then” branch of the conditional, x / y, has type Int, whereas the else branch, the call to error, has type Nothing. Because **Nothing **is a subtype of Int, the type of the whole conditional is Int, as required.

A good resource about Unit, Null and Nothing types in Scala:
https://kubuszok.com/2018/kinds-of-types-in-scala-part-1/

En escala no tengo tipos primitivos y null tiene su representación con nothing ?