以任意对象为参数的函数

Function taking any object as parameter

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

class A
class B

def foo[A](x: A) = typeOf[A] match {
    case x:A => println("this an A")
    case _ => println("no match")
  }
}

但这将被证明是无用的,因为没有匹配是可能的,我得到:

fruitless type test: a value of type runtime.universe.Type cannot also be a A

我想让 foo 接受 class 中的任何 type,从基本类型到自定义 classes。我该怎么做?

您可以使用ClassTag以下方式实现

import scala.reflect.ClassTag

def foo[A: ClassTag](x: A) = x match {
  case x: A => println(s"this an ${x.getClass}")
  case _ => println("no match")
}

A 可以是任何类型。