协变返回类型的实现

问题描述

我正在尝试为Scala中的方法实现协变返回类型。假设我们有以下情形:

class Animal
class Dog extends Animal
class Cat extends Animal

abstract class M[-T]{
  def get[U <: T](): U
}

val container = new M[Animal] {
  override def get[U <: Animal](): U = ???
}

我应该怎么做?

解决方法

例如,如果您只是好奇,可以使用Shapeless

import shapeless.{Generic,HNil}

def get[U <: Animal]()(implicit generic: Generic.Aux[U,HNil]): U = 
  generic.from(HNil)

get[Dog] // Dog() for case class,Dog@34340fab otherwise
get[Cat] // Cat() for case class,Cat@2aafb23c otherwise
get[Nothing] // doesn't compile
get[Null] // doesn't compile
get[Cat with Dog] // doesn't compile

或者您可以使用macro

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

def get[U <: Animal](): U = macro getImpl[U]

def getImpl[U: c.WeakTypeTag](c: blackbox.Context)(): c.Tree = {
  import c.universe._
  q"new ${weakTypeOf[U]}"
}

或者您可以使用runtime reflection

import scala.reflect.runtime.universe._
import scala.reflect.runtime

def get[U <: Animal : TypeTag](): U = {
  val typ = typeOf[U]
  val constructorSymbol = typ.decl(termNames.CONSTRUCTOR).asMethod
  val runtimeMirror     = runtime.currentMirror
  val classSymbol       = typ.typeSymbol.asClass
  val classMirror       = runtimeMirror.reflectClass(classSymbol)
  val constructorMirror = classMirror.reflectConstructor(constructorSymbol)
  constructorMirror().asInstanceOf[U]
}

(另请参见 @KrzysztofAtłasik的答案中有关Java反射的示例。)

或者您可以引入类型类并手动定义其实例

trait Get[U <: Animal] {
  def get(): U
}
object Get {
  implicit val dog: Get[Dog] = () => new Dog
  implicit val cat: Get[Cat] = () => new Cat
}

def get[U <: Animal]()(implicit g: Get[U]): U = g.get()
,

或者,您可以使用反射来创建新实例。您只需要获取隐式classTag

import scala.reflect.ClassTag

class Animal
class Dog extends Animal
class Cat extends Animal

abstract class M[-T] {
  def get[U <: T](implicit ct: ClassTag[U]): U
}

val container = new M[Animal] {
  override def get[U <: Animal](implicit ct: ClassTag[U]): U =
    //it gets no argument constructor so obviosly it will only work if your classes has no params
    ct.runtimeClass.getConstructor().newInstance().asInstanceOf[U]
}

container.get[Dog]