加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Scala中构造函数的通用参数

发布时间:2020-12-15 05:13:24 所属栏目:Java 来源:网络整理
导读:考虑以下设计的 Java示例: public class Example { private final Object value; private final List? aListOfTheseThings; public T Example(final T t,final ListT aListOfTheseThings) { this.value = t; this.aListOfTheseThings = aListOfTheseThings;
考虑以下设计的 Java示例:

public class Example {

    private final Object value;
    private final List<?> aListOfTheseThings;

    public <T> Example(final T t,final List<T> aListOfTheseThings) {
        this.value = t;
        this.aListOfTheseThings = aListOfTheseThings;
    }

}

我在这个例子中关心的是:

>示例未参数化
>构造函数是paremeterized并确保无论您传入什么,列表都在相同类型的t中参数化

(这是一个人为的例子,我并不关心(2)但我确实关心那里有一个类型参数,这个类参数在类的定义中没有提到).

现在在Scala中我尝试了以下方法:

class Example private[this](
  private val value: AnyRef,private val aListOfTheseThings: List[_]) {

  def this[T](t: T,aListOfTheseThings: List[T]) {
    this(t,aListOfTheseThings)
  }
}

……但这是不可能的.显然,类型参数在构造函数中无效(在此).

是否有机会将上述Java代码翻译成Scala?

解决方法

也许这个帮助:

sealed trait Example

object Example {
  def apply[T <: AnyRef](t:T,aListOfTheseThings: List[T]): Example = 
    new ExampleImpl(t,aListOfTheseThings)

  private class ExampleImpl(
    val value: AnyRef,val aListOfTheseThings: List[_]) extends Example 
}

这使得类的私有构造函数示例.不能通过Example trait访问value和aListOfTheseThings(除非你可以访问它)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读