简体   繁体   English

返回值的scala多态类型

[英]scala polymorphic type for return value

How would I make this pattern work? 我将如何使这种模式起作用? func() fails to compile. func()无法编译。 I understand the problem with this setup, but what's a pattern that could accomplish basically this? 我了解此设置的问题,但基本上可以完成此目标的模式是什么?

class A() {
  val a: Int = 123
  val b: String = "xxx"
}

def func[T](key: String, a: A): T = {
  if      (key == "a") a.a     // would make T an Int
  else if (key == "b") a.b     // would make T a String
}

val a = new A()
func[Int]("a", a)
func[String]("b", a)

I'm not quite sure what you are going for, but a few possibilities. 我不太确定您要做什么,但是有几种可能。

class A() {
  val a: Int = 123
  val b: String = "xxx"
}

def func[T : Manifest](a: A) = implictly[Manifest[T]] match {
  case implicitly[Manifest[Int]]) => a.a
  case implicitly[Manifest[String]) => a.b
}

val a = new A()
func[Int](a)
func[String](a)

or 要么

class A() {
  val a: Int = 123
  val b: String = "xxx"
}

val aKey = (_: A).a
val bKey = (_: A).b

def func[T](key: A => T, a: A) = key(a)

val a = new A()
func(aKey, a)
func(bKey, a)

or even with Shapeless , 甚至使用Shapeless

import shapeless._
import syntax.singleton._
import record._

val a = ("a" ->> 123) :: ("b"  ->> "xxx") :: HNil

a("a") // typed as an Int
b("b") // typed as a String

Maybe this is close to what you're after? 也许这接近您的追求?

class A() {
  val a: Int = 123
  val b: String = "xxx"
}

def func(key: String, a: A): Either[Int,String] = {
  if (key == "a") Left(a.a)
  else            Right(a.b)
}

val a = new A()
func("a", a)  // Left(123)
func("b", a)  // Right("xxx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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