I have a class which looks like this:
class X[A <: Throwable, B, C](b: B, c: C)
A, B and C can be inferred, so I can just instantiate it with:
val x = new X(3, 4)
which gives me an X[Nothing, Int, Int] - often what I want.
but I sometimes want to specify A to be something other than Nothing (say AssertionError). Is this possible without also specifying B and C. I imagined syntax along the lines of:
val x = new X[AssertionError](3, 4)
val x = new X[AssertionError, _, _](3, 4)
val x = new X[AssertionError,,](3, 4)
but obviously this doesn't work.
Is there some syntax for this, or some way I can achieve the same result?
The Scala compiler can infer the types of expressions automatically from contextual information. Therefore, we need not declare the types explicitly. This feature is commonly referred to as type inference. It helps reduce the verbosity of our code, making it more concise and readable.
Type declaration is a Scala feature that enables us to declare our own types. In this short tutorial, we'll learn how to do type declaration in Scala using the type keyword. First, we'll learn to use it as a type alias. Then, we'll learn to declare an abstract type member and implement it.
Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.
Here is my solution:
scala> class X[A <: Throwable, B, C](b: B, c: C)
defined class X
scala> class Builder[A <: Throwable] {
| def apply[B, C](b: B, c: C) = new X[A,B,C](b,c)
| }
defined class Builder
scala> def X[A <: Throwable]: Builder[A] = new Builder[A]
X: [A <: Throwable]=> Builder[A]
scala> val x = X[AssertionError](3, 4)
x: X[AssertionError,Int,Int] = X@2fc709
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With