How to pass implicit vals defined through package objects from Scala in Java2019 Community Moderator ElectionHow do I call one constructor from another in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?How do I copy an object in Java?How to pass an object from one activity to another on AndroidLoad Packages into Renjin in Scala or JavaScala 2.11 Type Variance ChangesScala implicit object vs implicit valFalse errors when using cats library in IntelliJImplementing subtype in traits throws error “Expected class or Object Defination”

Where is the fallacy here?

Plagiarism of code by other PhD student

How to mitigate "bandwagon attacking" from players?

Can a space-faring robot still function over a billion years?

What is a term for a function that when called repeatedly, has the same effect as calling once?

Being asked to review a paper in conference one has submitted to

School performs periodic password audits. Is my password compromised?

Meaning of word ягоза

PTIJ: What dummy is the Gemara referring to?

Script that counts quarters, dimes, nickels, and pennies

Deal the cards to the players

How do I deal with being envious of my own players?

Would the melodic leap of the opening phrase of Mozart's K545 be considered dissonant?

How can I handle a player who pre-plans arguments about my rulings on RAW?

Should we avoid writing fiction about historical events without extensive research?

Why is it "take a leak?"

Find maximum of the output from reduce

Create chunks from an array

Is there a way to find out the age of climbing ropes?

Why did the Cray-1 have 8 parity bits per word?

Specific Chinese carabiner QA?

Can the Shape Water Cantrip be used to manipulate blood?

How to disable or uninstall iTunes under High Sierra without disabling SIP

Is every open circuit a capacitor?



How to pass implicit vals defined through package objects from Scala in Java



2019 Community Moderator ElectionHow do I call one constructor from another in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?How do I copy an object in Java?How to pass an object from one activity to another on AndroidLoad Packages into Renjin in Scala or JavaScala 2.11 Type Variance ChangesScala implicit object vs implicit valFalse errors when using cats library in IntelliJImplementing subtype in traits throws error “Expected class or Object Defination”










3















I am using the Cats library. In Scala the code looks like:



import cats.Semigroupal
import cats.instances.option._
val r = Semigroupal.tuple2(Option(1), Option(2))


The tuple2 defined as:



def tuple2[F[_], A0, A1](f0:F[A0], f1:F[A1])(implicit semigroupal: Semigroupal[F], invariant: Invariant[F]):F[(A0, A1)]


The following implicit value is actually passed both as Semigroupal and as Invariant (checked via Intellij IDEA plugin for Scala):



package cats
package instances

trait OptionInstances ...
implicit val catsStdInstancesForOption: ...


How to pass catsStdInstancesForOption in tuple2 function from Java code?



Semigroupal$.MODULE$.tuple2(
Option.apply(1), Option.apply(2),
...,// and here?
... //here
);


Dependency on the Cats library, if needed:



<cats.core.version>1.5.0</cats.core.version>
...
<!-- https://mvnrepository.com/artifact/org.typelevel/cats-core -->
<dependency>
<groupId>org.typelevel</groupId>
<artifactId>cats-core_2.12</artifactId>
<version>$cats.core.version</version>
</dependency>









share|improve this question



















  • 1





    Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

    – Thilo
    19 hours ago











  • @Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

    – Alexandr
    19 hours ago















3















I am using the Cats library. In Scala the code looks like:



import cats.Semigroupal
import cats.instances.option._
val r = Semigroupal.tuple2(Option(1), Option(2))


The tuple2 defined as:



def tuple2[F[_], A0, A1](f0:F[A0], f1:F[A1])(implicit semigroupal: Semigroupal[F], invariant: Invariant[F]):F[(A0, A1)]


The following implicit value is actually passed both as Semigroupal and as Invariant (checked via Intellij IDEA plugin for Scala):



package cats
package instances

trait OptionInstances ...
implicit val catsStdInstancesForOption: ...


How to pass catsStdInstancesForOption in tuple2 function from Java code?



Semigroupal$.MODULE$.tuple2(
Option.apply(1), Option.apply(2),
...,// and here?
... //here
);


Dependency on the Cats library, if needed:



<cats.core.version>1.5.0</cats.core.version>
...
<!-- https://mvnrepository.com/artifact/org.typelevel/cats-core -->
<dependency>
<groupId>org.typelevel</groupId>
<artifactId>cats-core_2.12</artifactId>
<version>$cats.core.version</version>
</dependency>









share|improve this question



















  • 1





    Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

    – Thilo
    19 hours ago











  • @Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

    – Alexandr
    19 hours ago













3












3








3








I am using the Cats library. In Scala the code looks like:



import cats.Semigroupal
import cats.instances.option._
val r = Semigroupal.tuple2(Option(1), Option(2))


The tuple2 defined as:



def tuple2[F[_], A0, A1](f0:F[A0], f1:F[A1])(implicit semigroupal: Semigroupal[F], invariant: Invariant[F]):F[(A0, A1)]


The following implicit value is actually passed both as Semigroupal and as Invariant (checked via Intellij IDEA plugin for Scala):



package cats
package instances

trait OptionInstances ...
implicit val catsStdInstancesForOption: ...


How to pass catsStdInstancesForOption in tuple2 function from Java code?



Semigroupal$.MODULE$.tuple2(
Option.apply(1), Option.apply(2),
...,// and here?
... //here
);


Dependency on the Cats library, if needed:



<cats.core.version>1.5.0</cats.core.version>
...
<!-- https://mvnrepository.com/artifact/org.typelevel/cats-core -->
<dependency>
<groupId>org.typelevel</groupId>
<artifactId>cats-core_2.12</artifactId>
<version>$cats.core.version</version>
</dependency>









share|improve this question
















I am using the Cats library. In Scala the code looks like:



import cats.Semigroupal
import cats.instances.option._
val r = Semigroupal.tuple2(Option(1), Option(2))


The tuple2 defined as:



def tuple2[F[_], A0, A1](f0:F[A0], f1:F[A1])(implicit semigroupal: Semigroupal[F], invariant: Invariant[F]):F[(A0, A1)]


The following implicit value is actually passed both as Semigroupal and as Invariant (checked via Intellij IDEA plugin for Scala):



package cats
package instances

trait OptionInstances ...
implicit val catsStdInstancesForOption: ...


How to pass catsStdInstancesForOption in tuple2 function from Java code?



Semigroupal$.MODULE$.tuple2(
Option.apply(1), Option.apply(2),
...,// and here?
... //here
);


Dependency on the Cats library, if needed:



<cats.core.version>1.5.0</cats.core.version>
...
<!-- https://mvnrepository.com/artifact/org.typelevel/cats-core -->
<dependency>
<groupId>org.typelevel</groupId>
<artifactId>cats-core_2.12</artifactId>
<version>$cats.core.version</version>
</dependency>






java scala implicit scala-cats scala-java-interop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 18 hours ago







Alexandr

















asked 20 hours ago









AlexandrAlexandr

4,80284581




4,80284581







  • 1





    Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

    – Thilo
    19 hours ago











  • @Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

    – Alexandr
    19 hours ago












  • 1





    Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

    – Thilo
    19 hours ago











  • @Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

    – Alexandr
    19 hours ago







1




1





Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

– Thilo
19 hours ago





Maybe you should provide a Java-friendlier wrapper method (possibly specialized for the types you are going to need) written in Scala and call into that instead.

– Thilo
19 hours ago













@Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

– Alexandr
19 hours ago





@Thilo, I can. But I want to know, why I cannot use catsStdInstancesForOption in Java. I have hundred of methods with implicit values in the cats, it is not effective to write wrappers for all of them.

– Alexandr
19 hours ago












1 Answer
1






active

oldest

votes


















3














Referring to Scala objects defined inside package objects from Java is a pain, and as far as I can tell there's no good reason for this—it's entirely because of the way the compiler decides to mangle names (e.g. you can't refer directly to cats.instances.package$option$ from Java).



I've wanted to do this kind of thing before, and the best solution I've found is something like this:



import cats.Apply;
import cats.Semigroupal$;
import cats.instances.OptionInstances;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import scala.Option;
import scala.Tuple2;

public class Test
public static Apply<Option> getOptionInstance()
try
Class<?> cls = Class.forName("cats.instances.package$option$");
Field f = cls.getField("MODULE$");
Method m = f.getType().getMethod("catsStdInstancesForOption");
return (Apply<Option>) m.invoke(f.get(null));
catch (Exception e)
// Shouldn't happen but do something here anyway.
return null;



public static void main(String[] args)
Apply<Option> optionInstance = getOptionInstance();

Option<Tuple2<Integer, Integer>> pair = Semigroupal$.MODULE$.tuple2(
Option.apply(1),
Option.apply(2),
optionInstance,
optionInstance
);

System.out.println(pair);




It's terrible, but at least the reflection and casting are bundled up in one place.



If you have lots of instances you need to use from Java, you could abstract some of the logic out of getOptionInstance to cut down on repetition, but it's still not going to be fun. If you can write some utility code on the Scala side to use from Java, it wouldn't be too hard to make a more Java-friendly cats.instances—just don't use package objects, etc. (For what it's worth I wish Cats had kept more of an eye on Java-friendliness during its development, but as far as I can tell nobody else cared about that at all.)






share|improve this answer























  • great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

    – Alexandr
    18 hours ago











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55020829%2fhow-to-pass-implicit-vals-defined-through-package-objects-from-scala-in-java%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














Referring to Scala objects defined inside package objects from Java is a pain, and as far as I can tell there's no good reason for this—it's entirely because of the way the compiler decides to mangle names (e.g. you can't refer directly to cats.instances.package$option$ from Java).



I've wanted to do this kind of thing before, and the best solution I've found is something like this:



import cats.Apply;
import cats.Semigroupal$;
import cats.instances.OptionInstances;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import scala.Option;
import scala.Tuple2;

public class Test
public static Apply<Option> getOptionInstance()
try
Class<?> cls = Class.forName("cats.instances.package$option$");
Field f = cls.getField("MODULE$");
Method m = f.getType().getMethod("catsStdInstancesForOption");
return (Apply<Option>) m.invoke(f.get(null));
catch (Exception e)
// Shouldn't happen but do something here anyway.
return null;



public static void main(String[] args)
Apply<Option> optionInstance = getOptionInstance();

Option<Tuple2<Integer, Integer>> pair = Semigroupal$.MODULE$.tuple2(
Option.apply(1),
Option.apply(2),
optionInstance,
optionInstance
);

System.out.println(pair);




It's terrible, but at least the reflection and casting are bundled up in one place.



If you have lots of instances you need to use from Java, you could abstract some of the logic out of getOptionInstance to cut down on repetition, but it's still not going to be fun. If you can write some utility code on the Scala side to use from Java, it wouldn't be too hard to make a more Java-friendly cats.instances—just don't use package objects, etc. (For what it's worth I wish Cats had kept more of an eye on Java-friendliness during its development, but as far as I can tell nobody else cared about that at all.)






share|improve this answer























  • great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

    – Alexandr
    18 hours ago
















3














Referring to Scala objects defined inside package objects from Java is a pain, and as far as I can tell there's no good reason for this—it's entirely because of the way the compiler decides to mangle names (e.g. you can't refer directly to cats.instances.package$option$ from Java).



I've wanted to do this kind of thing before, and the best solution I've found is something like this:



import cats.Apply;
import cats.Semigroupal$;
import cats.instances.OptionInstances;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import scala.Option;
import scala.Tuple2;

public class Test
public static Apply<Option> getOptionInstance()
try
Class<?> cls = Class.forName("cats.instances.package$option$");
Field f = cls.getField("MODULE$");
Method m = f.getType().getMethod("catsStdInstancesForOption");
return (Apply<Option>) m.invoke(f.get(null));
catch (Exception e)
// Shouldn't happen but do something here anyway.
return null;



public static void main(String[] args)
Apply<Option> optionInstance = getOptionInstance();

Option<Tuple2<Integer, Integer>> pair = Semigroupal$.MODULE$.tuple2(
Option.apply(1),
Option.apply(2),
optionInstance,
optionInstance
);

System.out.println(pair);




It's terrible, but at least the reflection and casting are bundled up in one place.



If you have lots of instances you need to use from Java, you could abstract some of the logic out of getOptionInstance to cut down on repetition, but it's still not going to be fun. If you can write some utility code on the Scala side to use from Java, it wouldn't be too hard to make a more Java-friendly cats.instances—just don't use package objects, etc. (For what it's worth I wish Cats had kept more of an eye on Java-friendliness during its development, but as far as I can tell nobody else cared about that at all.)






share|improve this answer























  • great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

    – Alexandr
    18 hours ago














3












3








3







Referring to Scala objects defined inside package objects from Java is a pain, and as far as I can tell there's no good reason for this—it's entirely because of the way the compiler decides to mangle names (e.g. you can't refer directly to cats.instances.package$option$ from Java).



I've wanted to do this kind of thing before, and the best solution I've found is something like this:



import cats.Apply;
import cats.Semigroupal$;
import cats.instances.OptionInstances;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import scala.Option;
import scala.Tuple2;

public class Test
public static Apply<Option> getOptionInstance()
try
Class<?> cls = Class.forName("cats.instances.package$option$");
Field f = cls.getField("MODULE$");
Method m = f.getType().getMethod("catsStdInstancesForOption");
return (Apply<Option>) m.invoke(f.get(null));
catch (Exception e)
// Shouldn't happen but do something here anyway.
return null;



public static void main(String[] args)
Apply<Option> optionInstance = getOptionInstance();

Option<Tuple2<Integer, Integer>> pair = Semigroupal$.MODULE$.tuple2(
Option.apply(1),
Option.apply(2),
optionInstance,
optionInstance
);

System.out.println(pair);




It's terrible, but at least the reflection and casting are bundled up in one place.



If you have lots of instances you need to use from Java, you could abstract some of the logic out of getOptionInstance to cut down on repetition, but it's still not going to be fun. If you can write some utility code on the Scala side to use from Java, it wouldn't be too hard to make a more Java-friendly cats.instances—just don't use package objects, etc. (For what it's worth I wish Cats had kept more of an eye on Java-friendliness during its development, but as far as I can tell nobody else cared about that at all.)






share|improve this answer













Referring to Scala objects defined inside package objects from Java is a pain, and as far as I can tell there's no good reason for this—it's entirely because of the way the compiler decides to mangle names (e.g. you can't refer directly to cats.instances.package$option$ from Java).



I've wanted to do this kind of thing before, and the best solution I've found is something like this:



import cats.Apply;
import cats.Semigroupal$;
import cats.instances.OptionInstances;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import scala.Option;
import scala.Tuple2;

public class Test
public static Apply<Option> getOptionInstance()
try
Class<?> cls = Class.forName("cats.instances.package$option$");
Field f = cls.getField("MODULE$");
Method m = f.getType().getMethod("catsStdInstancesForOption");
return (Apply<Option>) m.invoke(f.get(null));
catch (Exception e)
// Shouldn't happen but do something here anyway.
return null;



public static void main(String[] args)
Apply<Option> optionInstance = getOptionInstance();

Option<Tuple2<Integer, Integer>> pair = Semigroupal$.MODULE$.tuple2(
Option.apply(1),
Option.apply(2),
optionInstance,
optionInstance
);

System.out.println(pair);




It's terrible, but at least the reflection and casting are bundled up in one place.



If you have lots of instances you need to use from Java, you could abstract some of the logic out of getOptionInstance to cut down on repetition, but it's still not going to be fun. If you can write some utility code on the Scala side to use from Java, it wouldn't be too hard to make a more Java-friendly cats.instances—just don't use package objects, etc. (For what it's worth I wish Cats had kept more of an eye on Java-friendliness during its development, but as far as I can tell nobody else cared about that at all.)







share|improve this answer












share|improve this answer



share|improve this answer










answered 18 hours ago









Travis BrownTravis Brown

117k9293562




117k9293562












  • great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

    – Alexandr
    18 hours ago


















  • great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

    – Alexandr
    18 hours ago

















great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

– Alexandr
18 hours ago






great answer. Thank you very much. Unfortunately the whole solution is ugly, but nevertheless it works! It seems a library for Scala should also provide some helper methods to be able to use the library classes from Java code.

– Alexandr
18 hours ago




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55020829%2fhow-to-pass-implicit-vals-defined-through-package-objects-from-scala-in-java%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved