Fixed type parameter in alternative constructor

Can this be done?

final case class C[A] (v: A) {
  def this() = this(true)
}

When building with this constructor, C is automatically C [Boolean]. This version does not compile, but it seems that it should be executed in some way, especially since the following seems to work:

final case class C[A] (v: A = true)

I need some compatibility with Java, so I try to avoid the defaults. I think I can achieve this using factory methods in a companion object, but can this be done directly? Since C is a case class, factory methods are a bit messy IMHO.

+4
source share
2 answers

, factory - , ( wheaties). , . :

final case class C[A] (v: A) {
  def this() = this("Hello".asInstanceOf[A]) // Compiles, thanks to type erasure
}

val c = new C[Int]() // Still compiles, despite the fact that "Hello" is not an Int
println(c) // C(Hello)
c.v + 1 // Compiles, but throws a ClassCastException at run-time

, , , . , , factory . , Java Interop factory . - :

// C.scala
final case class C[A] (v: A) 
object C {
    def apply(): C[Boolean] = C(true)
}

// Test.java
public class Test {
    public C c = C.apply();
}

scala Java, C$.

+2

object C{
  def apply() = C(true)
}

-? Java C$.apply() no?

+3

Source: https://habr.com/ru/post/1527939/


All Articles