3

The idea, is that, for example we got type of some object:

val tm = getTypeTag("String here").tpe
//> tm: reflect.runtime.universe.Type = java.lang.String

// for example I got another val or var, of some type:

val tmA: Any = "String here"
//> tmA: Any = String here

How to make tmA.InstanceOf(tm) (it is a mnemonic code)? 'Cause tm it is not a type alias, and we cant make InstanceOf[tm] exactly.

EDITED

there I mean analog function for asIstanceOf, to make a sort of type casting

EDITED2

I'll partly answer my question myself. So if we have TypeTags is is all easy!

def tGet[T](t: TypeTag[T], obj: Any): T = obj.asInstanceOf[T]

It is a harder situation if we only got Type and not the whole TypeTag[T].

2 Answers 2

6

You can use a mirror to reflect the instance:

val mirror = runtimeMirror(getClass.getClassLoader)

def isTm(a: Any) = mirror.reflect(a).symbol == tm.typeSymbol

And then:

scala> isTm("String here": Any)
res0: Boolean = true

scala> isTm(List("String here"): Any)
res1: Boolean = false

I don't think I have to tell you what a bad idea this is, though.

Sign up to request clarification or add additional context in comments.

3 Comments

thx for reply! that's right, and is not a good idea. but the idea, is that I have 100% sure, that the object is of that type. Mb I have a sort of mistake in my question, but I meant .asInstanceOf(tm) so to make a sort of casting.. so for example tm is ru.Type = String, and function myAsInstanceOf(tm) is in fact the same as asInstanceOf[String]
Oh, I did misunderstand then—I read InstanceOf as meaning isInstanceOf. I think you'll need a type tag (or macro) for the cast—I'll try to put together an answer when I get a chance.
thx! that would be great... And I'll try to avoid this, and post here, if it would be possible of cource.
-1

You need just to use type attribute of your variable after the variable. As an example you can write:

val h ="hello" val b:Any = "hhhh"

val stringB: String = b.asInstanceOf[h.type]

println(stringB)

1 Comment

But he's trying to cast to the type represented by a Type value (or a TypeTag value), not to the type of some given value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.