Accediendo a Scala.Ninguno de Java


¿Cómo se puede acceder a scala.None desde Java?

La última línea hace que el compilador muera con "type scala.Ninguno no toma parámetros".

import scala.Option;
import scala.Some;
import scala.None;
final Option<String> object1 = new Some<String>("Hi there");
final Option<String> object2 = new None<String>();

Esto falla con " cannot find symbol constructor None ()":

final Option<String> object2 = new None();

Esto falla con "no se puede encontrar la variable de símbolo Ninguno":

final Option<String> object2 = None;

En 2007 esto solía funcionar, pero luego Scala cambió. El compilador Java da error: incompatible types:

final Option<String> object2 = scala.None$.MODULE$;
Author: Mechanical snail, 2012-01-30

6 answers

Esto podría funcionar:

final scala.Option<String> x = scala.Option.apply(null);

Def aplicar [A] (x: A): Opción [A]
Una fábrica de opciones que crea Some (x) si el argumento no es null, y None si es null.

 31
Author: om-nom-nom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-11 14:02:53

Usando Scala 2.10.2 (no estoy seguro en qué versión cuando esto llegó):

final Option<String> none = Option.empty();
 15
Author: Dave Moten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-14 02:20:55

No es para poner un punto demasiado fino en él, pero uno no debe confiar en los reenviadores estáticos, ya que podrían no ser generados bajo ciertas circunstancias. Por ejemplo, Some no tiene reenviadores estáticos para su objeto compañero.

La forma actual de acceder a los métodos en un objeto compañero es la siguiente:

final scala.Option<String> x = scala.Option$.MODULE$.apply(null);

Option$ es la clase para el objeto compañero de Option. MODULE$ es un campo estático público final que contiene la única instancia de Option$ (en otras palabras, el objeto compañero).

 9
Author: Daniel C. Sobral,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-01 14:14:51

Puede importar

import scala.compat.java8.OptionConverters;

Y luego:

OptionConverters.<YourType>toScala(Optional.empty())
 1
Author: Christian Vielma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 16:05:45

Puedes hacer lo siguiente (lo probé y funciona bien para mí con Scala 2.9.1 y Java 1.6):

 final Option<String> obj1 = Some.apply(null) // This will give you a None;
 System.out.println(obj1.getClass()); // will print "class scala.None$

 final Option<String> obj2 = Some.apply("Something");
 System.out.println(obj2.getClass()); //will print "class scala.Some
 0
Author: vladmore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-30 05:29:44

Usando la versión 2.11.4 de Scala lo único que funcionó en mi caso fue

Option<String> maybeAmount = (amount != MISSING_STOCKAMOUNT) 
? Some.apply(amount+"") : Option.<String>apply(null); // can you feel the pain??

Actualización: un día después...

Option.apply(null);

Sin el parámetro type funciona también, como debería. Por alguna razón no pude conseguir que Intellij compilara el código en mi primer intento. Tuve que pasar el parámetro de tipo secundario. Ahora se compila, simplemente no preguntes

 0
Author: simou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-08 11:58:19