Generics: Type argument is not within its bounds - eclipse

Any idea why the following code wouldn't compile?
fun <T : Comparable<T>> naturalSort(list: List<T>): List<T> {
val natComparator = naturalOrder<T>() // compiler error here
return list.sortedWith(natComparator)
}
The second line results in the compiler error:
Type argument is not within its bounds: should be subtype of 'Comparable'
Update:
It works for me in https://play.kotlinlang.org/ but fails in Eclipse and when building the project (from Eclipse) with the project's Gradle build script.
Here's how my Gradle build environment looks like:
https://pastebin.com/0GDUWy2C

Solved. The problem was caused by the wrong Comparable interface being used due to import statements in the actual code (no problem with the import statements, not really sure why java.lang.Comparable was used instead of kotlin.Comparable). Specifying in the code that kotlin.Comparable should be used resolves the issue:
fun <T : kotlin.Comparable<T>> naturalSort(list: List<T>): List<T> {
val natComparator = naturalOrder<T>() // no error
return list.sortedWith(natComparator)
}
Thanks to everyone who responded.

Related

Why does AllOf() of Hamcrest is Ok in IDEA rather than Eclipse?

The following testing code can be compiled successfully in IDEA, while can not be compiled in Eclipse. The message from Eclipse is:
The method allOf(Matcher<? super T>, Matcher<? super T>) in the type Matchers is not applicable for the arguments (Matcher<Object[]>, Matcher<Double[]>).
I think the type of the first argument of allOf() is inferred as Matcher<Object>, while the type of the second as Matcher<Double>. But the allOf() requires the both arguments are the same. If this is the case, why does Eclipse do its inference in this way?
public class HamTest {
#Test
public void test() {
Double s[] = { 23.0, 65.0 };
assertThat(s, allOf(arrayWithSize(2), arrayContaining(lessThan(25.0), greaterThan(30.0))));
}
}
I got it. I think the ECJ compiler wrongly instantiate Matcher<E[]> to Matcher<Object[]> rather than Matcher<Double[]> for the arrayWithSize(). So I modified the calling of arrayWithSize(), then the compilation passed succesfully.
Matchers.<Double>arrayWithSize(2)

Java 8 Optional.ifPresent is my code wrong or is it eclipse?

I am new to Java 8 and trying out Null type annotations and Optional.
For my example below, I have used String rather than my class and am calling toUpperCase just to call something, in my case I actually call a function passing in a parameter (so don't think I can use :: operator and/or maps).
In Eclipse I have the Java - Compiler - Errors/Warnings - Null Analysis Errors turned on.
My test code below:
public void test1(#Nullable String s) {
// the 2nd s2 has a Potential null pointer access error.
// I was hoping ifPresent would imply NonNull
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
#Nullable
public String getSomeString() {
return null;
}
public void test2() {
String s = getSomeString();
// This is fine, unlike the first example, I would have assumed that
// it would know s was still nullable and behave the same way.
Optional.ofNullable(s).ifPresent(s2 -> s2.toUpperCase());
}
It would seem that using Eclipse type null annotations and Optional.ifPresent doesn't go well together.
Am I wasting my time trying to get something like this to work? Should I just revert back to assigning the getter to a temp var then checking if null, and if not call my function?
JDT's null analysis cannot know about the semantics of each and every method in JRE and other libraries. Therefore, no conclusions are drawn from seeing a call to ifPresent. This can be remedied by adding external annotations to Optional so that the analysis will see method ofNullable as
<T> Optional<#NonNull T> ofNullable(#Nullable T value)
External annotations are supported starting with Eclipse Mars, released June, 24, 2015. See Help: Using external null annotations.
The difference between the two variants in the question is due to how null analysis is integrated with Java 8 type inference: In variant (1) s has type #Nullable String. When this type is used during type inference, it is concluded that the argument to ifPresent is nullable, too. In variant (2) s has type String (although flow analysis can see that is may be null after the initialization from getSomeString). The unannotated type String is not strong enough to aid type inference to the same conclusion as variant (1) (although this could possibly be improved in a future version of JDT).
First of: #Nullable seams not to be part of the public Java 8 SDK. Have a look at the package you imported: com.sun.istack.internal.Nullable.
Second: I have run both of your methods: test1(null) and test2() and nothing out of the ordinary happened. Everything was fine (as expected). So what did you observe?
run test1(null) => no execution of lambda expression.
run test2() => no execution of lambda expression.
I changed your code for testing in the following way:
public void test1(#Nullable String s) {
Optional.ofNullable(s).ifPresent(s2 -> System.out.println("executed"));
}
public void test2() {
String s = getSomeString();
Optional.ofNullable(s).ifPresent(s2 -> System.out.println("executed"));
}

Scala - unbound wildcard exception (Play Framework 2.3 Template)

I am using Play Framework 2.3 I am using the scala template engine to create my views and Java elsewhere.
My model extends an abstract parameterised object like so... (pseudo code)
Abstract object:
public abstract class MyObject<T> {
// various bits
public class MyInnerObject {
// more stuff
}
}
Model object (singleton)
public class SomeModel extends MyObject<SomeBean> {
public static SomeModel getInstance() {
if (instance == null)
instance = new SomeModel();
return instance;
}
// more bits
}
I then pass the model to the view from another view helper:
#MyHelper(SomeModel.getInstance())
MyHelper scala view template:
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#doSomething(myInnerObj: MyObject[_]#MyInnerObject) = {
#* do some stuff *#
}
#for(myInnerObj <- myObj.getInnerObjects()) {
#doSomething(myInnerObj)
}
However I get an error on the line #doSomething(myInnerObj: MyObject[_]#MyInnerObject) stating
unbound wildcard exception
I am not sure the correct Scala syntax to avoid this error I had naively assumed that I could use the _ to specify arbitrary tyope but it won't let me do this.
What is the correct syntax?
UPDATE 1
Changing the method definition to:
#doSomething[T](myInnerObj: MyObject[T]#MyInnerObject)
gives further errors:
no type parameters for method doSomething: (myInnerObj:[T]#MyInnerObject)play.twirl.api.HtmlFormat.Appendable exist so that it can be applied to arguments (myObj.MyInnerObject)
--- because ---
argument expression's type is not compatible with formal parameter type;
found : myObj.MyInnerObject
required: MyObject[?T]#MyInnerObject
It would seem that the Twirl templating engine does not support this syntax currently, although I'm not 100% sure.
I can solve the problem by removing the doSomething method completely...
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#for(myInnerObj <- myObj.getInnerObjects()) {
<div>#myInnerObj.getSomeProperty()</div>
}
But I am bout 10% happy with the solution... It works at least but it feels very restricting that I cannot delegate to methods to help keep my code maintainable. By the look of the comments the problem seems to be a limitation in Twirl, not allowing type arguments for functions in views.
Note: I have accepted this answer as it removes the original problem of the exception however this is only because the solution I want doesn't exist... yet.

Is it true that for all .NET operator overload methods must be public and static?

Quoted from C# From CLR
The CLR specification mandates that operator overload methods be
public and static methods.
I checked ECMA-335, but couldn't find any evidence.
So far I know it is true for C# and F#. Is it true for all CLS-compliant language?
It looks like it's not really required to be public, but making it non-static is problematic at execution time. I experimented by starting with this code:
using System;
class Oddity
{
public static Oddity operator+(Oddity x, Oddity y)
{
Console.WriteLine("Adding oddities");
return null;
}
}
class Test
{
static void Main()
{
var x = new Oddity();
var y = new Oddity();
var z = x + y;
}
}
... and then running it through ildasm, changing things, then using ilasm and running the result.
Changing the accessibility modifier to assembly (equivalent to internal): all was fine
Changing the accessibility modifier to private: it assembled (which surprised me) but then failed at execution time:
Unhandled Exception: System.MethodAccessException: Attempt by method 'Test.Main()' to access method 'Oddity.op_Addition(Oddity, Oddity)' failed.
at Test.Main()
Removing the static part: it assembled (again, surprising me) but then failed at execution time:
Unhandled Exception: System.MissingMethodException: Method not found: 'Oddity Oddity.op_Addition(Oddity, Oddity)'.
at Test.Main()
I suspect these really should be caught at assembly time, but as languages are only expected to produce operators which are public and static, the validator is a little lax.

Scala problem with jMock expectations and returning a value from mock

Solved. IntelliJ didn't highlight the fact that my imports were incomplete.
Hi,
I have a simple Scala program that I'm trying to develop using jMock. Setting basic expectations works nicely but for some reason Scala does not understand my attempt to return a value from a mock object. My maven build spews out the following error
TestLocalCollector.scala:45: error: not found: value returnValue
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))
^
And the respective code snippets are
#Before def setUp() : Unit = { nodeCtx = context.mock(classOf[NodeContext]) }
...
// the value to be returned
val regex = ".*\\.data"
...
// setting the expectations
one (nodeCtx).getParameter("FilenameRegex"); will( returnValue(regex))
To me it sounds that Scala is expecting that the static jMock method returnValue would be a val? What am I missing here?
Are you sure about the ';'?
one (nodeCtx).getParameter("FilenameRegex") will( returnValue(regex))
might work better.
In this example you see a line like:
expect {
one(blogger).todayPosts will returnValue(List(Post("...")))
}
with the following comment:
Specify what the return value should be in the same expression by defining "will" as Scala infix operator.
In the Java equivalent we would have to make a separate method call (which our favorite IDE may insist on putting on the next line!)
one(blogger).todayPosts; will(returnValue(List(Post("..."))))
^
|
-- semicolon only in the *Java* version
The OP explains it himself:
the returnValue static method was not visible, thus the errors.
And the will method just records an action on the latest mock operation, that's why it can be on the next line or after the semicolon :)
import org.jmock.Expectations
import org.jmock.Expectations._
...
context.checking(
new Expectations {
{ oneOf (nodeCtx).getParameter("FilenameRegex") will( returnValue(".*\\.data") ) }
}
)