Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get companion object of class by given generic type Scala

What I am trying to do is to make a function that would take a generic class and use a static method in it (sorry for Java language, I mean method of its companion object).

trait Worker {def doSth: Unit}  class Base  object Base extends Worker  // this actually wouldn't work, just to show what I'm trying to achieve def callSthStatic[T that companion object is <: Worker](implicit m: Manifest[T]) {   // here I want to call T.doSth (on T object)   m.getMagicallyCompanionObject.doSth } 

Any ideas?

like image 727
Wojtek Erbetowski Avatar asked Feb 07 '12 08:02

Wojtek Erbetowski


People also ask

What is companion objects in Scala?

A companion object in Scala is an object that's declared in the same file as a class , and has the same name as the class. For instance, when the following code is saved in a file named Pizza.scala, the Pizza object is considered to be a companion object to the Pizza class: class Pizza { } object Pizza { }

Is companion object singleton in Scala?

In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object. The companion class and its companion object both must be defined in the same source file.

How do I use generic in Scala?

To use a generic class, put the type in the square brackets in place of A . The instance stack can only take Ints. However, if the type argument had subtypes, those could be passed in: Scala 2.

What is the advantage of companion objects in Scala?

Advantages of Companion Objects in Scala Companion objects provide a clear separation between static and non-static methods in a class because everything that is located inside a companion object is not a part of the class's runtime objects but is available from a static context and vice versa.


1 Answers

A gist by Miles Sabin may give you a hint:

trait Companion[T] {   type C   def apply() : C }  object Companion {   implicit def companion[T](implicit comp : Companion[T]) = comp() }  object TestCompanion {   trait Foo    object Foo {     def bar = "wibble"      // Per-companion boilerplate for access via implicit resolution     implicit def companion = new Companion[Foo] {       type C = Foo.type       def apply() = Foo     }   }    import Companion._    val fc = companion[Foo]  // Type is Foo.type   val s = fc.bar           // bar is accessible } 

This should be compiled with the -Ydependent-method-types flag if using Scala 2.9.x.

like image 153
3 revs, 3 users 78% Avatar answered Oct 05 '22 10:10

3 revs, 3 users 78%