简体   繁体   中英

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. Is it possible to do something like the below in 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.

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. 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 . I'm not aware of any way around this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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