How to use scala.None from Java code [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Accessing scala.None from Java
In Java you can create an instance of Some using the constructor, i.e. new Some(value), but None has no partner class. How do you pass None to a Scala function from Java?

The scala.None$.MODULE$ thing doesn't always typecheck, for example this doesn't compile:
scala.Option<String> x = scala.None$.MODULE$;
because javac doesn't know about Scala's declaration-site variance, so you get:
J.java:3: incompatible types
found : scala.None$
required: scala.Option<java.lang.String>
scala.Option<String> x = scala.None$.MODULE$ ;
This does compile, though:
scala.Option<String> x = scala.Option.apply(null);
so that's a different way to get a None that is usable in more situations.

I think this ugly bit will work: scala.None$.MODULE$
There is no need for a new instance since one None is as good as another...

You can access the singleton None instance from java using:
scala.None$.MODULE$

I've found this this generic function to be the most robust. You need to supply the type parameter, but the cast only appears once, which is nice. Some of the other solutions will not work in various scenarios, as your Java compiler may inform you.
import scala.None$;
import scala.Option;
public class ScalaLang {
public static <T> Option<T> none() {
return (Option<T>) None$.MODULE$;
}
}
public class ExampleUsage {
static {
//for example, with java.lang.Long
ScalaLang.<Long>none();
}
}

Faced with this stinkfest, my usual modus operandi is:
Scala:
object SomeScalaObject {
def it = this
}
Java:
doStuff(SomeScalaObject.it());

Related

Generics and Comparator

I am working on generics and found that the following code is giving compile time error at comparing method.
Multiple markers at this line
- Cannot infer type argument(s) for comparing(Function)
- The type A does not define m1(Object) that is applicable here
class A<T> {
String m1() {
return null;
}
}
class B {
void test() {
Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1);
}
}
Can some one help me understand this behavior; and how can I fix the problem?
If you specify the exact generic types at the comparing method, the code compiles.
Comparator<A<String>> target =
Comparator.<A<String>, String>comparing(A::m1).thenComparing(A::m1);
You should specify type parameter for class A.
Comparator<A<String>> target = Comparator.comparing(A<String>::m1).thenComparing(A<String>::m1);
Interesting question. Haven't gone into JLS but I guess type inference does not work in case of chained method call. (You can see it works for a simple Comparator<A<String>> target = Comparator.comparing(A<String>::m1); )
One quick fix, which is similar to another answer, is help Java do the type inference:
Comparator<A<String>> target = Comparator.comparing(A<String>::m1)
.thenComparing(A::m1);
Please note doing it at the first method already do the trick.
(Looking forward to see if someone can dig out JLS to see if such inference is supposed to be valid :P )
you can nested as
Comparator<A<String>> target1 = Comparator.comparing(A::m1);
Comparator<A<String>> target2 = target1.thenComparing(A::m1);
myVarList.sort(target2);
Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1);
thenComparing() expects a Comparator object as parameter...

How to get the parameter values of a called method in java? [duplicate]

This question already has answers here:
Retrieving parameter values through reflection
(2 answers)
Closed 9 years ago.
I'm trying to get some runtime information to do some debugging. Is there a way to access the parameters actually passed to a method?
I know the calling class and method, but not the parameters and their value at runtime. Any Ideas how to solve this? Thanks in advance.
My code so far:
//get the class I wanna know something about out of the call history
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String callerMethod = stacktrace[2].getMethodName();
//load the class to get the information
Class<?> c = Class.forName(stacktrace[2].getClassName());
Method[] methods = c.getMethods();
Class<?>[] parameters = methods[1].getParameterTypes();
//get the parameter data
(parameters[y].isArray()? parameters[y].getComponentType() : parameters[y]).getName();
//TODO: how about the parameter value at runtime?
The code has to be generic for all Classes I will implement. Example of usage:
public class doClass() {
public void doSomething(Object o) {
//here comes my debug line
magicDebugger(level);
}
}
level is the switch/trigger to activate console/db/file/mail output or whatever of some information
I expect following output (maybe there's some System.out.println in the magicDebugger class):
[debug] caller: com.company.package.doClass.doSomething(Object o); value of o at runtime = java.lang.String "test"
you can use http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html
Proxy class or AspectJ framework to do that
Look into using reflection for this. That should provide what you're looking for.

need help translating a code snippet from java to C# equivalent

Here's the code snippet I'd like to translate from Java to C#. I'm not sure what's causing the error but I've never used ArrayLists and vectors before. Thanks in advance!!
//Java class definitions, constructors, fields, methods etc here.
//sphbasis is a Vector object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.toArray(
new SphericalHarmonicDecomposition[sphbasislist.size()]));
}
I've tried doing the following in C#:
//C# class definitions, constructors, fields, methods etc here.
//sphbasis is a ArrayList object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray(
new SphericalHarmonicDecomposition[sphbasislist.Count]));
}
I get the following errors. I'm using Mono and Xamarin studio on a mac.
Error CS1502: The best overloaded method match for
`System.Collections.ArrayList.ToArray(System.Type)'
has some invalid arguments (CS1502) (projectx)
and
Error CS1503: Argument `#1' cannot convert
`matdcal.engine.model.SphericalHarmonicDecomposition[]' expression
to type `System.Type' (CS1503) (projectx)
Please try the following. In Java you need to pass an array to the toArray method, but that's not correct in C# (.NET).
//C# class definitions, constructors, fields, methods etc here.
//sphbasis is a ArrayList object.
public SphericalHarmonicDecomposition[] getSphericalHarmonicBasis() {
return (SphericalHarmonicDecomposition[])(sphbasislist.ToArray());
}
References
Java ArrayList.toArray
C# List.ToArray

how to define a class variable referring to an object of same class in python [duplicate]

This question already has answers here:
Can a class variable be an instance of the class?
(2 answers)
Closed 9 years ago.
Below is java code. I need to know the equivalent code in python:
class A {
public static A obj = new A();
}
You can't do this inside a python class definition, since the class has not yet been defined until the end of the class: block. You will have to set it after:
class A(object):
pass
A.obj = A()
You could do this with a metaclass:
class SelfReferencingObjectMetaclass(type):
def __new__(cls, name, bases, attrs):
attrs['obj'] = property(lambda self: self.__class__.obj)
return super(SelfReferencingObjectMetaclass, cls).__new__(cls, name, bases, attrs)
#property
def obj(cls):
try:
return cls._obj
except AttributeError:
cls._obj = cls()
return cls._obj
class A(object):
__metaclass__ = SelfReferencingObjectMetaclass
As #Daniel Roseman notes in the comments to #jamylak's answer though, there's probably an easier, more Pythonic way to solve the problem you have than this. Following that comment, how you would accomplish this functionally, if not identically in terms of the object structure, would be by having a module like this:
a.py
class A(object):
#property
def obj(self):
return a_inst
a_inst = A()
This does create the somewhat ugly construct from a import A in code that utilizes it, but it's a less complicated way to implement it.
Do you need this class member before any instance of the class is created? In not, you can try assigning it when the first instance is created:
class A (object):
obj = None
def __init__(self):
if A.obj is None:
a.obj = A()
# or:
a.obj = self
I think you'd like to do that because you're trying to implement a pattern like singleton or something like that.
You may read the following recipe from activestate: http://code.activestate.com/recipes/52558/
It explains the way it works and also shows some code.

Re-using Java generic collections in Scala without trait Object

I'm trying to re-use a Java generic collection I wrote, looks a lot like this:
public class Blah<T>
implements List<T>
{
...
public void test(T[] array) {
...
}
...
}
When consumed from a Scala generic collection that uses the above, I'm getting a compilation error, where I notice that the Blah class method expects not T, but T with java.lang.Object!
Object MyStaticObject {
def test[T](array: Array[T]) = {
val x = new Blah[T]();
x.test(array) // <- error here: Overloaded method with alternatives test[T with java.lang.Object] ... cannot be applied
}
Is there a way to avoid this situation without re-writing the Blah class in Scala? (That works, but I have too much such Java code and rather not port the whole thing...)
Maybe perhaps some kind of implicit definition could come to the rescue?
Thanks!
Restricting def test[T <: AnyRef] does the trick.
Rightly so, the generic java method should not accept , e.g., an int[] (Array[Int]) parameter.
Blah[Int] will be taken as Blah<Integer>, Array[Int] is int[], which is not Integer[].

Categories