Scala中的一个方法,它不接受任何参数并使用泛型类型 [英] A method in Scala that takes no arguments and uses a generic type

查看:136
本文介绍了Scala中的一个方法,它不接受任何参数并使用泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Scala中编写一个不带参数的方法,并且将使用泛型类型在方法中执行一些逻辑,该方法将仅基于泛型类型返回输出(类似于 asInstanceOf [T] isInstanceOf [T] )。

I'm trying to write a method in Scala that will take no arguments and will use a generic type to perform some logic in the method that will return output solely based on the generic type (similar to asInstanceOf[T] or isInstanceOf[T]).

它应该是这样的:

It should be something like this:

val myObj = new MyClass
myObj.instanceOf[MyClass]
// returns true

这是我认为可能会发挥作用。

This is what I thought may work.

class MyClass {
  def instanceOf[Class[_]]: Bool = {
    // ???
  }
}

如何实现这个?

谢谢。

推荐答案

您可以使用ClassTags获取传入的类型并使用它。

You could grab the type that was passed in by using ClassTags and use that.

标题中提到的一个人为的例子是:

A contrived example of what is asked in the title would be:

class Foo(name: String) {
  def nameMatches[T: ClassTag]() =
    classTag[T].runtimeClass.getName == name
}

new Foo("java.lang.String").nameMatches[String] //> res1: Boolean = true
new Foo("boolean").nameMatches[Boolean]         //> res2: Boolean = true

这篇关于Scala中的一个方法,它不接受任何参数并使用泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆