php redeclaring function like in java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php function overloading
I want to redeclare function such like this:
class Name{
function a(){ something; }
function a($param1){ something; }
}
but it returns
Fatal error: Cannot redeclare Name::a()
In java it just works. How can I do this in PHP?

Use default parameters:
class Name{
function a($param1=null){ something; }
}
If no parameter is passed to Name::a() it will assign a $param1 has a value of null. So basically passing that parameter becomes optional. If you need to know if it has a value or not you can do a simple check:
if (!is_null($param1))
{
//do something
}

You won't redeclare a function. Instead you can make an argument optional by assigning a default value to it. Like this:
function a($param1 = null){ something; }

Function arguments to not uniquely identify a function. In Java the arguments are strictly defined. This allows the compiler to know which function you are calling.
But, in PHP this is not the case.
function a()
{
$args = func_get_args();
foreach($args as $value)
{
echo $value;
}
}
It's possible to create function that has no arguments define, but still pass it arguments.
a("hello","world")
would output
hello world
As a result, PHP can't tell the different between a() and a($arg). Therefore, a() is already defined.
PHP programmers have different practices to handle this single function problem.
You can define an argument with default values.
a($arg = 'hello world');
You can pass mixed variable types.
function a($mixed)
{
if(is_bool($mixed))
{
.....
}
if(is_string($mixed))
{
.....
}
}
My preference is to use arrays with defaults. It's a lot more flexible.
function a($options=array())
{
$default = array('setting'=>true);
$options = array_merge($default,$options);
....
}
a(array('setting'=>false);

Unfortunately PHP does not support Method overloading like Java does. Have a look at this here for a solution: PHP function overloading
so func_get_args() is the way to go:

Related

Proper usage of Optional.ifPresent()

I am trying to understand the ifPresent() method of the Optional API in Java 8.
I have simple logic:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));
But this results in a compilation error:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)
Of course I can do something like this:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}
But this is exactly like a cluttered null check.
If I change the code into this:
user.ifPresent(new Consumer<User>() {
#Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});
The code is getting dirtier, which makes me think of going back to the old null check.
Any ideas?
Optional<User>.ifPresent() takes a Consumer<? super User> as argument. You're passing it an expression whose type is void. So that doesn't compile.
A Consumer is intended to be implemented as a lambda expression:
Optional<User> user = ...
user.ifPresent(theUser -> doSomethingWithUser(theUser));
Or even simpler, using a method reference:
Optional<User> user = ...
user.ifPresent(this::doSomethingWithUser);
This is basically the same thing as
Optional<User> user = ...
user.ifPresent(new Consumer<User>() {
#Override
public void accept(User theUser) {
doSomethingWithUser(theUser);
}
});
The idea is that the doSomethingWithUser() method call will only be executed if the user is present. Your code executes the method call directly, and tries to pass its void result to ifPresent().
In addition to #JBNizet's answer, my general use case for ifPresent is to combine .isPresent() and .get():
Old way:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}
New way:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})
This, to me, is more intuitive.
Why write complicated code when you could make it simple?
Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...
if (user.isPresent())
{
doSomethingWithUser(user.get());
}
This code has the advantages of being
readable
easy to debug (breakpoint)
not tricky
Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.
You can use method reference like this:
user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);
Method ifPresent() get Consumer object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user.
Or if this method doSomethingWithUser is in the User class and it is not static, you can use method reference like this:
user.ifPresent(this::doSomethingWithUser);
Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent() . Example:
list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());

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

What is the Java equivalent of a JavaScript callback? [duplicate]

This question already has answers here:
Java Pass Method as Parameter
(17 answers)
Closed 9 years ago.
I am experienced in JavaScript but new to Java. I am trying to figure out how to pass a function as a parameter of another function. In JavaScript this would like the block in Figure 1.
Figure 1
function fetchData(url, callback) {
// Do ajax request and fetch data from possibly slow server
// When the request is done, call the callback function
callback(ajaxResponse);
}
Is there a similar way of doing this in Java? I have searched the internets, but found little that is helpful on a novice level.
Unfortunately, the only equivalent (that I know if) is defining an interface which your fetchData method will accept as a parameter, and instantiate an anonymous inner class using that interface. Or, the class calling the fetchData method can implement that interface itself and pass its own reference using this to method.
This is your method which accepts a "callback":
public void fetchData(String url, AjaxCompleteHandler callback){
// do stuff...
callback.handleAction(someData);
}
The definition of AjaxCompleteHandler
public interface AjaxCompleteHandler{
public void handleAction(String someData);
}
Anonymous inner class:
fetchData(targetUrl, new AjaxCompleteHandler(){
public void handleAction(String someData){
// do something with data
}
});
Or, if your class implements MyCoolInterface, you can simply call it like so:
fetchData(targetUrl, this);

Check javascript function is defined from java applet

I am developing a Java applet where I call a javascript function:
boolean isAllowed = (boolean) win.eval("isPointMarkCreationAllowed()");
and I would like to check if that function exists, like we do in javascript:
if (isPointMarkCreationAllowed == 'function')
is there anyway to do that in Java?
Without actually having tried it, wouldn't
win.eval("typeof isPointMarkCreationAllowed == 'function'");
do exactly what you want and return a Boolean (true or false)?
You can use reflection to test if a method exists.
For example if you have an object foo, you can get all the methods declared in the class of that object in the following:
Method[] methods = foo.getClass().getMethods();
This returns an array of the methods declared in the class.
Then just use a for loop to check if a specific method exists in the array returned
for (Method m : methods)
{
if (m.getName().equals(someString))
{
//do something
}
}
someString is the name of the method you're looking for, which is "isPointMarkCreationAllowed" in your case.
Use the following site to learn about reflections in Java
http://docs.oracle.com/javase/tutorial/reflect/member/methodType.html

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

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());

Categories