简体   繁体   English

是否可以在Scala中匹配函数的返回类型?

[英]Is it possible to match on a function's return type in Scala?

I'm pretty new to Scala, so still figuring out what the type inference system can do. 我对Scala还是很陌生,所以仍然要弄清楚类型推断系统可以做什么。 Is it possible to do something like the below in Scala? 是否可以在Scala中执行以下操作?

abstract class BaseBar
class DerivedBar1 Extends BaseBar
class DerivedBar2 Extends BaseBar

def foo[T]: List[T] = {
  <T type> match {
    case DerivedBar1 => getSomethingOfTypeDerivedBar1
    case DerivedBar2 => getSomethingOfTypeDerivedBar2
  }
}

... and then be able to safely call ...然后可以安全地致电

val myDerivedBar1 = foo[DerivedBar1]()

... or ... 要么

def getBar: DerivedBar2 = foo()

You can match on the method's type parameter by "un-erasing" it with an implicit ClassTag parameter. 您可以通过使用隐式ClassTag参数“取消擦除”方法来匹配方法的type参数。

import scala.reflect.ClassTag

def foo[T](implicit t: ClassTag[T]) = t.runtimeClass match { /* ... */ }

As for inference based on the expected return type: Scala does use that context as part of its type inference, but I think you're going to have trouble getting it to do what you want here. 至于基于预期返回类型的推断:Scala确实将该上下文用作其类型推断的一部分,但我认为您将很难使其在此处执行所需的操作。 For example: 例如:

def bar[T](implicit t: ClassTag[T]): List[T] = { println(t.runtimeClass); Nil }
val x: List[String] = bar

You'd probably expect/hope that this would print class java.lang.String , but it will actually print class scala.runtime.Nothing$ because it's the most general choice to infer for T . 您可能希望/希望这将打印class java.lang.String ,但实际上它会打印class scala.runtime.Nothing$因为这是推断T的最一般的选择。 I'm not aware of any way around this. 我不知道有什么办法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM