St.Antario
St.Antario

Reputation: 27375

Specify generic type parameter in Scala

I'm new to Scala and have generic method written in Java:

public interface Context{
    <T> Optional<T> get(String parameterName);
}

and Scala class:

class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

Upvotes: 0

Views: 169

Answers (3)

Dima
Dima

Reputation: 40500

val str: Optional[String] = ctx.get("str") should do it.

And so should val str = ctx.get[String]("str")

Upvotes: 3

Alexey Romanov
Alexey Romanov

Reputation: 170713

asInstanceOf[Optional[String]] is just incorrect in this case, even though it happens to work due to type erasure. To specify the parameter directly you'd write

ctx.get[String]("str")

which is the direct equivalent to ctx.<String> get("str") in Java.

Upvotes: 2

chengpohi
chengpohi

Reputation: 14217

I think you can use type alias to short this, and it's unnecessary to cast the type.

  type MY_TYPE = Optional[String]
  val str: MY_TYPE = ctx.get("str") //it's unnecessary get in here, since the `get` method already return `MY_TYPE`, and specify type after variable, the compiler will auto infer the generic type for this.
  println(str)

Upvotes: 1

Related Questions