Kotlin unresolved reference linkedListOf - android-studio

Following this post http://obviam.net/index.php/libgdx-and-kotlin/ I
created a project, and edited using Atom. It compiles, and runs on an android device. I want to convert to AndroidStudio for better tooling.
I'm using AndroidStudio 1.5.1, and it says I have the latest version of the kotlin plugin. I created a new project using the LibGDX setup program, imported into AdroidStudio, converted the main class to kotlin, everything works. Then I pasted in my existing my code, and when I build, this line:
val bullets:MutableList<NewBullet> = linkedListOf()
gets this error:
Error:(19, 42) Unresolved reference: linkedListOf
When I select Tools -> Kotlin -> Configure it says 'All modules with Kotlin files are configured'.
I've also tried importing the existing project into AndroidStudio, and the result is the same issue.

As said in the change log of Kotlin 1.0 RC, linkedListOf has been deprecated and is not available now. The article you referenced uses Kotlin 1.0 Beta, which is older.
To create a LinkedList<T> from varargs, you can pass a listOf(...) to the constructor:
val bullets: MutableList<SomeType> = LinkedList(listOf(item1, item2))
or write your own linkedListOf:
fun <T> linkedListOf(vararg items: T) = LinkedList<T>().apply {
for (i in items) { add(i) }
}

Related

Groovy how can I build a custom library and use it in a project as dependency

I have a set of code procedures I use in a lot of places and I'm trying to basically move it to a library.
So I created my library with some unit test and everything was looking promising and at least working localy..
When I went to my project and deleted the files locally and then try to import them from my library as a dependency the code does not work.
I always get this kind of error
Class does not define or inherit an implementation of the resolved method abstract getProperty(Ljava/lang/String;)Ljava/lang/Object; of interface groovy.lang.GroovyObject.
I'm definitely not an expert on groovy but basically I use it in my Jenkins and Gradle for pipelines and some basic packaging or environment deployments.
I can show my class:
class ConsoleRow implements Comparable {
...
final Integer priority
final String rowStatus
final String message
final String rowReportClass
ConsoleRow(Integer priority, String status, String msg, String rowC) {
this.priority = priority
this.rowStatus = status
this.message = msg
this.rowReportClass = rowC
}
#Override
int compareTo(Object o) {
return this.priority <=> ((ConsoleRow) o).priority
}
The line that gives me the error is this actual compareTo when trying to do the "this.priority"
Caused by: java.lang.AbstractMethodError: Receiver class com.abc.insight.jenkins.ConsoleRow does not define or inherit an implementation of the resolved method abstract getProperty(Ljava/lang/String;)Ljava/lang/Object; of interface groovy.lang.GroovyObject.
at com.abc.insight.jenkins.ConsoleRow.compareTo(ConsoleRow.groovy:24)
at com.abc.insight.jenkins.ConsoleOutputHtmlBuilder.processOutput(ConsoleOutputHtmlBuilder.groovy:115)
at com.abc.insight.jenkins.ConsoleOutputHtmlBuilder.processOutput(ConsoleOutputHtmlBuilder.groovy)
at com.abc.insight.jenkins.ConsoleOutputHtmlBuilder.buildReport(ConsoleOutputHtmlBuilder.groovy:20)
at com.abc.insight.jenkins.ConsoleOutputHtmlBuilder$buildReport.call(Unknown Source)
at build_e548mc0tqjmi822clitlsycdk.runReport(C:\dev\repo\insight\insight-health-check\data-foundation\smoke-test\build.gradle:77)
The calling function is just trying to sort a list of those objects
List<ConsoleRow> outputRows = []
...
return outputRows.sort()
The part that gets me really confused is that if instead of importing the library as a dependency I just do this directly in this repo and put my sources in my buildSrc\src\main\groovy\com\abc\insight the code works fine...
So I really think it might be how I package and publish my library that might be wrong.
I'm really sure this is some basic error on my part because I never did a groovy library before but somehow I can't make it work.
It might be that my publication is just wrong, on my library side I'm using this plugins to do the publishing.
plugins {
id 'groovy'
id 'java-library'
id 'base'
}
publishing {
publications {
maven(MavenPublication) {
from components.java
}
}
}
I tried to change components.groovy but somehow it does not work.
Any ideas or tips, I think my question probably is showing some really lack of know-how on groovy but looking at the documentation and examples I could not figure it out.
Doing some debug in my IDE the compareTo that generates the exception looks like this.
public int compareTo(Object o) {
CallSite[] var2 = $getCallSiteArray();
return ScriptBytecodeAdapter.compareTo(this.priority, var2[0].callGroovyObjectGetProperty((ConsoleRow)ScriptBytecodeAdapter.castToType(o, ConsoleRow.class)));
}
I tried following this guide and code structure when doing moving the code to a library
https://docs.gradle.org/current/samples/sample_building_groovy_libraries.html
Thanks for any feedback
p.s: My code might look weird, I tried first to have everything with the def blablabla but I was having some issues with typecasting but I don't think this would be the reason for the problem I'm facing.
Anyway I got a look at the generated code in my IDE and I see a lot of get methods just no idea where they expected this getProperty from
Ok this was definitely a user error.
I am using distribution version of gradle 6.5.1
When I did the gradle init to bootstrap my project I was provided with the dependency of gradle groovy-all version 2.5.11
implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.5.11'
I thought that was a mistake and just updated to the latest version.
implementation group: 'org.codehaus.groovy', name: 'groovy-all', version: '3.0.9'
Now the problem is that the project in which I'm using the library is also running with gradle 6.5.1 so probably this version missmatch between compiple and usage was causing the problem.
By reverting to the correct version suggested by gradle the problem is gone.

Android Studio 3 beta 2 ClassNotFound in kotlin unit tests

I am using Android Studio 3.0 beta 2, converted an existing project to gradle plugin 3.0.0-beta2
When I try to run an existing unit test written in kotlin I get 'java.lang.NoClassDefFoundError: com/other/domain/CollectionItem'
The test itself is very simple:
import org.junit.Test
import org.junit.Assert.*
class CollectionViewModelTest {
#Test
fun getItemsWithManyItemsWillReturnCollectionItemViewModels() {
val collectionItems = listOf(CollectionItem(42, "Item1", CollectionItemType.COLLECTION, ""), CollectionItem(43, "Item2", CollectionItemType.COLLECTION, ""), CollectionItem(44, "Item3", CollectionItemType.COLLECTION, ""))
val collection = Collection(45, "Home", "Home collection", collectionItems, 42)
val collectionViewModel = CollectionViewModel(collection)
assertTrue(collectionViewModel.items.first().isFirst)
assertFalse(collectionViewModel.items.first().isLast)
assertFalse(collectionViewModel.items[1].isFirst)
assertFalse(collectionViewModel.items[1].isLast)
assertTrue(collectionViewModel.items.last().isLast)
assertFalse(collectionViewModel.items.last().isFirst)
}
}
It works when I run it from the terminal using ./gradlew
Any ideas why this can happen?
Edit:
This seems to happen only when the test requires classes from other library projects.
In this case CollectionItem is part of another library in the same project and it's included in the gradle file via implementation project(':domain')
Edit
It might also be worth mentioning that domain module is pure java
Edit
Figured out the problem is when the library (domain) has classes written in kotlin, those classes will throw NoClassDefFoundError in unit test's only.

Choosing different libraries for compilation and runtime

I have two libraries with same classes defined in each one. However they have some different contents (methods/constants).
For example:
Library 1:
package com.test.package;
Class A {
// only method signatures
public void methodA() {
}
public void methodB() {
}
}
Library 2:
package com.test.package;
Class A {
public void methodA() {
// some logic that MUST be executed to provide backward compatibility
}
}
My application uses Library 1 and Library 2 and run in devices which have com.test.package.ClassA, but com.test.package.ClassA.methodB() will only exist in newer releases in framework. Said that, I need the Library 1 to be used to compile my application and the Library 2 to execute a different implementation of methodA().
I have tried to do this in Android Studio using .jar and .aar libraries format, but none of them worked for me.
Is it possible to set this configuration in an Android Studio project?
I am building both Library 1 and 2, and I cannot add methodB() in Library 2.
For a simple Java application, you can do this by unlinking the compile and runtime configurations. I set up an example repository here.
The idea is shown in this commit, but can be described as manually resetting the runtime configuration so that it doesn't include the contents of the compile configuration. After doing so, you can just include your runtime library variation in the runtime configuration.
The application's build.gradle becomes something like:
apply plugin: 'application'
mainClassName = 'my.package.MyAppClass'
configurations.runtime.extendsFrom = [] // Reset runtime configuration
dependencies {
compile 'my.group:my.artifact:2.0' // Library 1, with the new method
runtime 'my.group:my.artifact:1.0' // Library 2, without the method
}
For Android, this can be a little more complicated. The problem is that there's no runtime configuration for Android (because you don't execute it on your computer, unless you're using Robolectric or something similar).
I think there are a few workarounds you can probably use, but one initial suggestion would be to create a wrapper library that abstracts away the dependency on the other libraries. This wrapper library you can compile with the newest library version (Library 1, with the new method). You could then include the wrapper library in the Android app while setting it as a non-transitive dependency and including the other library version:
dependencies {
compile 'my.group:my.wrapped.artifact:0.1' {
transitive = false // Don't include dependencies of the wrapper
// i.e., don't include version 2.0 of the lib.
}
compile 'my.group:my.artifact:1.0'
}
This should work because by setting the dependency as non-transitive Gradle doesn't recursively include the dependencies of the wrapper library, so the version used to compile the wrapper isn't included (in theory) in the APK. You can therefore add the old version without causing a conflict.
An example is set up in the same repository, under the Android branch. Firstly, two Java libraries are created. Then an Android library is created to wrap around the compile-time library. An example activity is created to show how using the wrapper library uses the compile-time library. Then, the latest commit shows how the app is configured to use the wrapper library (which compiles with the newest library) but forces the old library to be included instead in the runtime.
Hope this helps =)

Create external link in Javadoc using Gradle in Android Studio

I have created a Gradle task that generates a javadoc using Doclava:
My code (the arguments of some of my methods) references classes defined in Android. When Javadoc is built, these references link correctly to the Android online reference. However, when I use the #ling tag to link to Android references, it does not work and I get something like:
configurations {
jaxDoclet
classpaths
}
dependencies {
// For Doclava JavaDoc
jaxDoclet("com.google.doclava:doclava:1.0.6")
classpaths files('build/intermediates/classes/debug')
classpaths project.files(android.getBootClasspath().join(File.pathSeparator))
}
task javadoc(type: Javadoc) {
source = android.sourceSets.main.allJava
source += fileTree("build/generated/source/r/debug")
title = null
options {
docletpath = configurations.jaxDoclet.files.asType(List)
doclet "com.google.doclava.Doclava"
bootClasspath new File(System.getenv('JAVA_HOME') + "/jre/lib/rt.jar")
classpath += configurations.classpaths.files.asType(List)
addStringOption "public"
addStringOption "federate android", "http://d.android.com/reference"
addStringOption "federationxml android", "http://doclava.googlecode.com/svn/static/api/android-10.xml"
}
}
warning 101: Unresolved link/see tag "Runnable" in com....
In similar questions in SO, it was advised to use -link and -linkoffline flags. However, when I do that I get:
javadoc: error - invalid flag: -linkoffline
I am using Android Studio 1.5.1 and Gradle 2.11.
Update
It seems that Doclava may not support -link and -linksoffline according to these tickets. If I use the default doclet, links work correctly.

Xamarin Linker : Default constructor not found for type Cirrious.CrossCore.IoC.MvxPropertyInjector

With a skeleton project with FirstView from HotTuna package, and with Build linker behavior set to "Link all assemblies", I get the following error:
System.MissingMethodException: Default constructor not found for type Cirrious.CrossCore.IoC.MvxPropertyInjector
Using NuGet package v3.1.1 for all MvvmCross (4 packages)
LinkerPleaseInclude file does have the line
[MonoTouch.Foundation.Preserve(AllMembers = true)]
Using the latest stable build:
On PC:
Xamarin for VS 1.12.278
Xamarin.iOS 1.12.278
Mac:
Xamarin.iOS 7.2.2.2
Of course with Linker behavior of SDK only, it runs fine. Any suggestions anyone?
Solved; So, with the basic project, there were three consecutive errors in the following order:
System.MissingMethodException: Default constructor not found for type Cirrious.CrossCore.IoC.MvxPropertyInjector
can be resolved either by --linkskip=Cirrious.Core (ugly), or by including the following in LinkerPleaseInclude.cs
public void Include(MvxPropertyInjector injector){
injector = new MvxPropertyInjector ();
}
Next error is:
Cirrious.CrossCore.Exceptions.MvxException: Failed to construct and initialize ViewModel for type {0} from locator MvxDefaultViewModelLocator - check MvxTrace for more information
This one is difficult; Simple fix is to ofcourse to do a --linkskip=portableLibrary, or to crate an instance of the ViewModel somewhere (perhaps in LinkerPleaseInclude.cs); problem with the second approach at-least in my case is, most of my VM doesn't have a parameter less constructor, and obviously using IOC in this case wouldn't help.
Final Error:
System.ArgumentNullException: missing source event info in MvxWeakEventSubscription
Parameter name: sourceEventInfo
Either use --linkskip=System (ugly), or add the following to LinkerPleaseInclude.cs
public void Include(INotifyPropertyChanged changed)
{
changed.PropertyChanged += (sender, e) => {
var test = e.PropertyName;
};
}
This was enough for my basic project to run with LinkAllAssemblies, Using LLVM optimizer, and Use SGen collector.
Hope this will help anyone looking for a solution.
I hit this when my XCode was out of sync with the latest Xamarin on my Mac. Upgrading XCode to the latest resolved the problem.

Resources