我如何在Scala中设置多个ORed类型边界 [英] How do I setup multiple ORed type bounds in Scala

查看:103
本文介绍了我如何在Scala中设置多个ORed类型边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Scala 中这样做:

  class MyTest {
def foo [A< ;: String _or_ A<:Int](p:List [A])= {}

$ / code>

即类型 A 可以是字符串 Int 。这可能吗?



(类似的问题

不像你说的那样真的可行,但你可以使用类型模式进行操作。例如,从此处

 密封的抽象类可接受的[T] 
对象可接受的{
隐式对象IntOk extends Acceptable [Int]
隐式对象LongOk extends Acceptable [Long]
}

def f [T:可接受](t:T)= t

scala> f(1)
res0:Int = 1

scala> f(1L)
res1:长= 1

scala> f(1.0)
< console>:8:错误:找不到参数ev的隐式值:可接受[Double]
f(1.0)
^

$ b $ p $编辑

这适用于类和对象是同伴。在REPL上,如果您在不同的行上键入每个行(即它们之间出现结果),则它们不是同伴。不过,您可以像下面那样键入它:

  scala>密封抽象类可接受[T];对象可接受{
|隐式对象IntOk扩展Acceptable [Int]
|隐式对象LongOk扩展Acceptable [Long]
| }
定义的类可接受的
定义的模块可接受的


Is it possible to do something like this in Scala:

class MyTest {
   def foo[A <: String _or_ A <: Int](p:List[A]) =  {} 
}

That is, the type A could be a String or Int. Is this possible?

(Similar question here)

解决方案

Not really possible as you put it, but you can do it using the type class pattern. For example, from here:

sealed abstract class Acceptable[T]
object Acceptable {
  implicit object IntOk extends Acceptable[Int]
  implicit object LongOk extends Acceptable[Long]
}

def f[T: Acceptable](t: T) = t

scala> f(1)
res0: Int = 1

scala> f(1L)
res1: Long = 1

scala> f(1.0)
<console>:8: error: could not find implicit value for parameter ev: Acceptable[Double]
f(1.0)
^

EDIT

This works if class and object are companions. On REPL, if you type each on a different line (ie, a "result" appears between them), they are not companions. You can type it like below, though:

scala> sealed abstract class Acceptable[T]; object Acceptable {
     |   implicit object IntOk extends Acceptable[Int]
     |   implicit object LongOk extends Acceptable[Long]
     | }
defined class Acceptable
defined module Acceptable

这篇关于我如何在Scala中设置多个ORed类型边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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