tôi viết những chuyển đổi ngầm sau trong scala:Tại sao loại chuyển đổi ngầm này là bất hợp pháp?
implicit def strToInt2(str: String):Int = {
str.toInt
}
Nhưng nó tăng lên lỗi này biên soạn:
<console>:9: error: type mismatch;
found : str.type (with underlying type String)
required: ?{val toInt: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method augmentString in object Predef of type (x: String)scala.collection.
immutable.StringOps
and method toi in object $iw of type (str: String)Int
are possible conversion functions from str.type to ?{val toInt: ?}
str.toInt
^
Nếu tôi loại bỏ các kiểu trả về, chỉ cần khai báo nó như thế này:
implicit def strToInt2(str: String) = {
str.toInt
}
Nó biên dịch thành công. Bất cứ ai có thể cho tôi biết sự khác biệt giữa hai là gì?
Không biết câu trả lời chính xác, nhưng tôi cho rằng có một chuỗi chuyển đổi tiềm ẩn -> int trong Predef. Vì vậy, việc thêm chuyển đổi mới của các loại đó làm cho mọi thứ trở nên mơ hồ. – dmitry