Scala reflection: can I see if something is a (case) object?












1















Is there a way in Scala to see if a class was defined as an object?



def isObject(c: Class[_]): Boolean = ???

object X
class Y

val x = X
val y = new Y

isObject(x.getClass) == true
isObject(y.getClass) == false









share|improve this question


















  • 2





    Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

    – Suma
    Nov 23 '18 at 18:52











  • It's not important, just curiosity.

    – jqno
    Nov 25 '18 at 8:14
















1















Is there a way in Scala to see if a class was defined as an object?



def isObject(c: Class[_]): Boolean = ???

object X
class Y

val x = X
val y = new Y

isObject(x.getClass) == true
isObject(y.getClass) == false









share|improve this question


















  • 2





    Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

    – Suma
    Nov 23 '18 at 18:52











  • It's not important, just curiosity.

    – jqno
    Nov 25 '18 at 8:14














1












1








1


1






Is there a way in Scala to see if a class was defined as an object?



def isObject(c: Class[_]): Boolean = ???

object X
class Y

val x = X
val y = new Y

isObject(x.getClass) == true
isObject(y.getClass) == false









share|improve this question














Is there a way in Scala to see if a class was defined as an object?



def isObject(c: Class[_]): Boolean = ???

object X
class Y

val x = X
val y = new Y

isObject(x.getClass) == true
isObject(y.getClass) == false






scala reflection






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 12:57









jqnojqno

11.1k64766




11.1k64766








  • 2





    Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

    – Suma
    Nov 23 '18 at 18:52











  • It's not important, just curiosity.

    – jqno
    Nov 25 '18 at 8:14














  • 2





    Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

    – Suma
    Nov 23 '18 at 18:52











  • It's not important, just curiosity.

    – jqno
    Nov 25 '18 at 8:14








2




2





Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

– Suma
Nov 23 '18 at 18:52





Why is this important for you? What difference is for you between val obj = new Y or val obj = new AnyRef { } or object obj {}?

– Suma
Nov 23 '18 at 18:52













It's not important, just curiosity.

– jqno
Nov 25 '18 at 8:14





It's not important, just curiosity.

– jqno
Nov 25 '18 at 8:14












2 Answers
2






active

oldest

votes


















4














Using scala-reflect, following seems to work:



object ObjectReflection extends App {

import scala.reflect.runtime.universe._

def isObject[T](x: T)(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) {
case SingleType(_, _) => true
}

object AnObject
case object ACaseObject
class AClass
case class ACaseClass(i: Int)
trait ATrait

println("new AClass " + isObject(new AClass))
println("ACaseClass(42) " + isObject(ACaseClass(42)))
println("new ATrait {} " + isObject(new ATrait {}))
println("AnObject " + isObject(AnObject))
println("ACaseObject " + isObject(ACaseObject))

}


Prints:



new AClass     false
ACaseClass(42) false
new ATrait {} false
AnObject true
ACaseObject true


Depends on:



libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value





share|improve this answer


























  • I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

    – ygor
    Nov 25 '18 at 11:38



















1














As a first approximation, you can do



def isObject(c: Class[_]): Boolean = c.getName.endsWith("$")


because the anonymous class created for a singleton object y has name y$, and the usual anonymous classes (such as new AnyRef {}) end in $<number> instead.



But it's legal to create class y$ as well, which would give a false positive; such names are rare in practice, though.



Using scala-reflect should allow a more precise answer.






share|improve this answer

























    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%2f53447160%2fscala-reflection-can-i-see-if-something-is-a-case-object%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    Using scala-reflect, following seems to work:



    object ObjectReflection extends App {

    import scala.reflect.runtime.universe._

    def isObject[T](x: T)(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) {
    case SingleType(_, _) => true
    }

    object AnObject
    case object ACaseObject
    class AClass
    case class ACaseClass(i: Int)
    trait ATrait

    println("new AClass " + isObject(new AClass))
    println("ACaseClass(42) " + isObject(ACaseClass(42)))
    println("new ATrait {} " + isObject(new ATrait {}))
    println("AnObject " + isObject(AnObject))
    println("ACaseObject " + isObject(ACaseObject))

    }


    Prints:



    new AClass     false
    ACaseClass(42) false
    new ATrait {} false
    AnObject true
    ACaseObject true


    Depends on:



    libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value





    share|improve this answer


























    • I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

      – ygor
      Nov 25 '18 at 11:38
















    4














    Using scala-reflect, following seems to work:



    object ObjectReflection extends App {

    import scala.reflect.runtime.universe._

    def isObject[T](x: T)(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) {
    case SingleType(_, _) => true
    }

    object AnObject
    case object ACaseObject
    class AClass
    case class ACaseClass(i: Int)
    trait ATrait

    println("new AClass " + isObject(new AClass))
    println("ACaseClass(42) " + isObject(ACaseClass(42)))
    println("new ATrait {} " + isObject(new ATrait {}))
    println("AnObject " + isObject(AnObject))
    println("ACaseObject " + isObject(ACaseObject))

    }


    Prints:



    new AClass     false
    ACaseClass(42) false
    new ATrait {} false
    AnObject true
    ACaseObject true


    Depends on:



    libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value





    share|improve this answer


























    • I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

      – ygor
      Nov 25 '18 at 11:38














    4












    4








    4







    Using scala-reflect, following seems to work:



    object ObjectReflection extends App {

    import scala.reflect.runtime.universe._

    def isObject[T](x: T)(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) {
    case SingleType(_, _) => true
    }

    object AnObject
    case object ACaseObject
    class AClass
    case class ACaseClass(i: Int)
    trait ATrait

    println("new AClass " + isObject(new AClass))
    println("ACaseClass(42) " + isObject(ACaseClass(42)))
    println("new ATrait {} " + isObject(new ATrait {}))
    println("AnObject " + isObject(AnObject))
    println("ACaseObject " + isObject(ACaseObject))

    }


    Prints:



    new AClass     false
    ACaseClass(42) false
    new ATrait {} false
    AnObject true
    ACaseObject true


    Depends on:



    libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value





    share|improve this answer















    Using scala-reflect, following seems to work:



    object ObjectReflection extends App {

    import scala.reflect.runtime.universe._

    def isObject[T](x: T)(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) {
    case SingleType(_, _) => true
    }

    object AnObject
    case object ACaseObject
    class AClass
    case class ACaseClass(i: Int)
    trait ATrait

    println("new AClass " + isObject(new AClass))
    println("ACaseClass(42) " + isObject(ACaseClass(42)))
    println("new ATrait {} " + isObject(new ATrait {}))
    println("AnObject " + isObject(AnObject))
    println("ACaseObject " + isObject(ACaseObject))

    }


    Prints:



    new AClass     false
    ACaseClass(42) false
    new ATrait {} false
    AnObject true
    ACaseObject true


    Depends on:



    libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 25 '18 at 8:50









    Suma

    21.5k890155




    21.5k890155










    answered Nov 24 '18 at 9:03









    ygorygor

    1,088615




    1,088615













    • I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

      – ygor
      Nov 25 '18 at 11:38



















    • I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

      – ygor
      Nov 25 '18 at 11:38

















    I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

    – ygor
    Nov 25 '18 at 11:38





    I hardcoded scala version into the dependency, which is quite wrong. Thanks @Suma for the edit ! Also edited: stackoverflow.com/questions/53326545/… and stackoverflow.com/questions/53391593/…

    – ygor
    Nov 25 '18 at 11:38













    1














    As a first approximation, you can do



    def isObject(c: Class[_]): Boolean = c.getName.endsWith("$")


    because the anonymous class created for a singleton object y has name y$, and the usual anonymous classes (such as new AnyRef {}) end in $<number> instead.



    But it's legal to create class y$ as well, which would give a false positive; such names are rare in practice, though.



    Using scala-reflect should allow a more precise answer.






    share|improve this answer






























      1














      As a first approximation, you can do



      def isObject(c: Class[_]): Boolean = c.getName.endsWith("$")


      because the anonymous class created for a singleton object y has name y$, and the usual anonymous classes (such as new AnyRef {}) end in $<number> instead.



      But it's legal to create class y$ as well, which would give a false positive; such names are rare in practice, though.



      Using scala-reflect should allow a more precise answer.






      share|improve this answer




























        1












        1








        1







        As a first approximation, you can do



        def isObject(c: Class[_]): Boolean = c.getName.endsWith("$")


        because the anonymous class created for a singleton object y has name y$, and the usual anonymous classes (such as new AnyRef {}) end in $<number> instead.



        But it's legal to create class y$ as well, which would give a false positive; such names are rare in practice, though.



        Using scala-reflect should allow a more precise answer.






        share|improve this answer















        As a first approximation, you can do



        def isObject(c: Class[_]): Boolean = c.getName.endsWith("$")


        because the anonymous class created for a singleton object y has name y$, and the usual anonymous classes (such as new AnyRef {}) end in $<number> instead.



        But it's legal to create class y$ as well, which would give a false positive; such names are rare in practice, though.



        Using scala-reflect should allow a more precise answer.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 19:03

























        answered Nov 23 '18 at 18:49









        Alexey RomanovAlexey Romanov

        106k25209350




        106k25209350






























            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%2f53447160%2fscala-reflection-can-i-see-if-something-is-a-case-object%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

            Berounka

            Sphinx de Gizeh

            Fiat S.p.A.