vaibhavpops
vaibhavpops

Reputation: 1

Scala generics not clear to me

class A {

    def x(): Unit = {
      println("tftf")
    }

}

def t[A](x: A): Unit = {
    x.x    // <- error at this line 
}

I get compile error - type mismatch; found : x.type (with underlying type A) required: ?{def x: ?} Note that implicit conversions are not applicable because they are ambiguous: both method any2Ensuring in object Predef of type [A](x: A)Ensuring[A] and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A] are possible conversion functions from x.type to ?{def x: ?} - t

Can someone explain this in English, please? I am new to Scala.

Upvotes: 0

Views: 147

Answers (4)

middlewareman
middlewareman

Reputation: 1

There are two sources of confusion here:

  1. Your type parameter A shadows class type A.

  2. Type parameter A is unconstrained, which implicitly means [A <: Any], and Any doesn't have the member x. The confusing error message comes from the compiler attempting to apply an implicit conversion from Any to something that has a member x.

You simply want a function that takes a parameter that is a subtype of A, but you don't need a type parameter for this since any subtype of class type A is a valid substitution for class type A as a function parameter.

Hence the solution is simply this:

def t(a: A) {
    a.x()
}

Upvotes: 0

cloud
cloud

Reputation: 1065

in your def t[A](x: A), A is a generic type parameter and has nothing to do with the class A you defined. you can name it whatever you want, like def t[T](x: T).

what you want to do actually is:

def t[B <: A](x: B): Unit = {
   x.x    //  won't error
}

Upvotes: 2

Chris Martin
Chris Martin

Reputation: 30756

t's generic parameter named A shadows the class named A.

What you've written is equivalent to:

class A {
    def x(): Unit = {
      println("tftf")
    }
}

def t[B](x: B): Unit = {
    x.x    // <- error at this line 
}

Upvotes: 5

Michael Zajac
Michael Zajac

Reputation: 55569

In your example, A is a concrete type (a class). But in the function t[A](x: A): Unit, you're trying to use it as a type parameter. There's nothing generic about it.

A simple example of using generics with the function would be something like:

def t[A](x: A): Unit = println("Here is the parameter x: " + x)

This function will accept any type, and simply print it to the console.

Upvotes: 3

Related Questions